Lookup a control at an arbitrary level of the Page hierarchy
In ASP.NET 2.0 the page hierarchy often happens to be deeper than it was with the older version, mostly when using MasterPages. Consequently, when you want to obtain a reference to a control of the page given its ID and you don't know at which level of the hierarchy it is placed, using the FindControl() method of the Page object isn't the right way of proceding since it just performs a search among the direct children of the page itself.
In such cases you may use a recursive search, which walks all the page hierarchy. Note that you should use this workaround only when you strictly need it, because it could introduce a consistent overhead in the processing of the page due to the fact that everything becomes a control when on the server, and you'll find yourself looping through a considerable number of controls. This is a recursive implementation of the method:
public static Control FindControl(string controlId, ControlCollection controls)
{
foreach (Control control in controls)
{
if(control.ID == controlId)
return control;
if(control.HasControls())
{
Control nestedControl = FindControl(controlId, control.Controls);
if(nestedControl != null)
return nestedControl;
}
}
return null;
}
Then you can simply use it this way:
Control foundControl = FindControl(controlToFindID, Page.Controls);