Find Deeply Nested Child Objects in any Container with Recursion and Extensions
We’ve all hit the problem of trying to find a deeply nested control and you loathe to say MyControl1.Controls[2].Controls[4].Controls[0] as it’s going to break at the first html change.
This function loops through an object and all nested objects until it finds the name you are after and breaks out.
This is also an extension method, so it can be called as a native method of any object that inherits from System.Web.UI.Control. This method is very fast by the way.
TextBox foundControl =
MyControl.FindControlRecursive("MyTextBox") as TextBox;
method:
public static Control FindControlRecursive(
this Control parentControl,
string findId)
{
if (parentControl.ID == findId)
{
return parentControl;
}
if (parentControl.HasControls())
{
foreach (Control subControl in parentControl.Controls)
{
Control found = subControl.FindControlRecursive(findId);
if (found != null)
{
return found;
}
}
}
return null;
}