public static class MyExtensionMethods
{
public static Control FindControlRecursive(this Control root, string id)
{
if (0 == id.CompareTo(root.ID))
{
return root;
}
foreach (Control childControl in root.Controls)
{
Control foundControl = FindControlRecursive(childControl, id);
if (null != foundControl)
{
return foundControl;
}
}
return null;
}
}
Now I can just call Page.FindControlRecursive("txtSomeControl"); in either the MasterPage or Non-MasterPage scenarios and expect the method to behave the same in both scenarios.
Sunday, November 1, 2009
How can I find ChildControls on ASP.NET Pages within a MasterPage?
I know this isn't really exciting or cutting edge, but hopefully you'll find it useful. Occasionally I need to use the FindControl method on an ASP.NET WebForms page to locate a particular control. Recently I needed to do the same on a web site was using MasterPages which causes the Page.FindControl to not find thte controls on the page as you would expect. This is because the Page object is now contained in a MasterPage, so you have to drill down the control heirarchy. In this case I was able to solve my problem by writing an extension method to the Control class that recursively searches for the specified control. Here's what the method ended up looking like:
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment