Alright, I'm going to have a lot of blog posts over the next few days going over my wonderful expereinces learning how to create advanced server controls, and just how hard it is to find good information on the subject. But the problem I ran into today was having Page.FindControl() not work as expected.
Problem
Page.FindControl() can be misleading. A developer without understanding the situation could assume FindControl() will return a control found within that page. This is completely wrong. The reason this does not work is because Page does not have its own FindControl() function. It actually inherits this from Control, because Page inherits control. So FindControl() is really more like a FindChildrenControls(), and it is not recursive.
Example
I have some code that does a Page.FindControl() for a GridView. However, later I move the GridView into an UpdatePanel to add ajax enabled stuff. All of a sudden my Page.FindControl() doesn't work. The reason? Because my GridView is no longer a direct child of the Page and it is now a child of the UpdatePanel. So instead of being Page -> GridView it is Page -> UpdatePanel -> GridView.
Solution
I found a blog post for a recursive post. Here is the code:
-
private Control FindControlRecursive(Control root, string id)
-
{
-
if (root.ID == id)
-
{
-
return root;
-
}
-
-
foreach (Control c in root.Controls)
-
{
-
Control t = FindControlRecursive(c, id);
-
if (t != null)
-
{
-
return t;
-
}
-
}
-
-
return null;
-
}
No related posts.

9 Responses
Comments RSS Feed.
thx for that post, it was quite helpful and made me understand the innner workings of asp.net a little better
Thank you sooooooooooooooooo much
You’re welcome
I haven’t used ASP.NET for almost a year now, but I’m glad my findings still help people out.
Thank you. Thank you. Thank you.
I am kind of a rookie to ASP.Net controls. I created a dynamicPanel Control (custom) for doing partial refreshes with AJAX. I cant find the control on a page using a masterpage and a content panel. What would be the value for the “Control Root”?
Thank you.
This is great!
Thanks so much!
Thank Heavens! I spent a little bit of time on this and was pulling my hair out. Thanks for saving me potential hours!