Using C# to Recursively Call FindControl in ASP.NetRecursively Call FindControl using this function which will not only search on the page, but the component containers as well.
In ASP.Net I often need to Recursively Call FindControl to get an object reference to a control on the ASPX page. The only problem with this is that you need to know the control that it is contained with. This recursive method will search for a given control within a parent control and all its child controls.
public static Control FindControlRecursive(Control container, string name)
{
if ((container.ID != null) && (container.ID.Equals(name)))
return container;
foreach (Control ctrl in container.Controls)
{
Control foundCtrl = FindControlRecursive(ctrl, name);
if (foundCtrl != null)
return foundCtrl;
}
return null;
}
Usage
You need to pass in two parameters, a reference to a control to look into and the name of the control to find.
Example:
Control myControl = FindControlRecursive(PlaceHolder1, "myControl");