The missing FindControl() method
Most ASP.NET developers have probably used the FindControl() method before. It lives as a member of the Control class, way up in the inheritance hierarchy. Most also know that it's limited to finding only immediate child controls, unless you specify the UniqueID. That always seemed weird when you used the method from the Page object, because you'd think it would go deeper.
But then I wondered how it was that data-bound controls were getting references to the DataSource controls. I fired up Reflector (best tool ever!) and looked under the hood to see what was going on. As it turns out, there's an internal class called System.Web.UI.WebControls.DataBoundControlHelper with a static method called FindControl(), taking the parent control and the ID you're searching for as parameters. The code looks something like this:
public static Control FindControl(Control control, string controlID)
{
Control control1 = control;
Control control2 = null;
if (control == control.Page)
{
return control.FindControl(controlID);
}
while ((control2 == null) && (control1 != control.Page))
{
control1 = control1.NamingContainer;
if (control1 == null)
{
throw new HttpException(SR.GetString("DataBoundControlHelper_NoNamingContainer", new object[] { control.GetType().Name, control.ID }));
}
control2 = control1.FindControl(controlID);
}
return control2;
}
I'm left wondering why the design decision was made to not make this a public class. I found use for the very same code today when implementing a non-rendering control that manipulates other stuff on the page.