FindControl Method makes better way by using extension method

The default implementation of the FindControl method which is part of the Control class is not recursive. This means that if you are trying to find a TextBox control “txtUserName” which is nested inside a FormView control you cannot use the following code:

Page.FindControl("txtUserName");

The reason is that the txtUserName is not contained inside the Page control but actually is a part of the FormView control. So, the only way to access the txtUserName is to use the FindControl method of the FormView control.

FormView1.FindControl("txtUserName");

Sometimes we just need to get the control without knowing about the parent of the control. In this case we will create our own FindControl method.

public static class ExtensionMethods
{
public static T BetterFindControl<T>(this Control root, string id) where T : Control
{
if (root != null)
{
if (root.ID == id) return root as T;
var foundControl = (T) root.FindControl(id);
if (foundControl != null) return foundControl;
foreach (Control childControl in root.Controls)
{
foundControl = (T) BetterFindControl<T>(childControl, id);
if (foundControl != null) return foundControl as T;
}
}
return null;
}
}

I have set up the BetterFindControl method as an extension method for the Control class. Now, I can access the “txtUserName” TextBox directly from the Page class using the following code:

var tb = Page.BetterFindControl<TextBox>("txtUserName");

Althought this works just fine but it has side effects. Consider that you page contains lots of Grids and rich controls. And the control that you are trying to find is located at the end of the page. Then using the Page.BetterFindControl(‘id”) would not be a good idea since it will first check all the controls in its path which will kill performance.
So, it is always a good idea to know who is the parent of the searched control. A better use of BetterFindControl<T> method will be when searching inside a Wizard control or any other template based control.

Tagged . Bookmark the permalink.

Leave a Reply