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 in and the name of the control to find.
Example:
Control myControl = FindControlRecursive(PlaceHolder1, "myControl");
@roy : your function is nice but return type should be T instead of Control, otherwise using templates is pretty useless....
private T GetControl<T>(Control Container, string ControlID) where T : Control
Good post. This is the one we use.
<code>
private Control GetControl<T>(Control Container, string ControlID) where T : Control
{
T result = Container.FindControl(ControlID) as T;
if (result == null)
{
foreach (Control c in Container.Controls)
{
result = this.GetControl<T>(c, ControlID) as T;
if (result != null)
{
break;
}
}
}
return result;
}
</code>