Thursday, May 29, 2008

Find a Control in ASP.Net Page

One ASP.NET page is composed of one aspx or xml file for front-end UI design and a class either in C# or VB as server side codes related to the page and control events.

Unlike window form application, the code-behind class does not know controls on the page directly. You cannot directly access control instances. For example, a label or text box control within a GridView control's template.

Here is one function I use to get a control by id:

using System.Web.UI;
...
public class WebPageUtil
{
...
public static T FindControlRecursive<T>(Control root, string id) where T: Control
{
T found = null;
if (root != null)
{
found = root.FindControl(id) as T;
if (found == null)
{
if (root.ID == id)
{
found = root as T;
}
else if (root.Controls != null)
{
foreach (Control ctr in root.Controls)
{

found = FindControlRecursive(ctr, id);
if (found != null)
{
break;
}
}
}
}
}

return found;
}
...
}


Where Control is a System.Web.UI.Control. It has FindControl() method. It can only find control within a container control, or root in this case. For example, in a GridView control named as GridView1, a TableCell control in a selected row (GridView1.Rows[0]) may contain some Label or TextBox controls, which are defined within aspx page GridView1 control's template.

However, this call only search for controls directly placed within the current control. If the control is within the next or even deep level, you have to loop its children Controls to call recursively.

I use generic type method call to make the method very simple to use. Here are some examples:

GridViewRow row = GridView1.Rows[e.RowIndex] // e is GridViewUpdateEventArgs object
LinkButton btnSave = WebPageUtil.FindControlRecursive<LinkButton>(row, "btnSave");
if (btnSave != null)
btnSave.Visible = false;

0 comments: