Jeff and .NET

The .NET musings of Jeff Putz

Sponsors

News

My Sites

Archives

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. 

Posted: Nov 08 2006, 07:02 PM by Jeff | with 3 comment(s)
Filed under:

Comments

.NET Junkie said:

I was wondering this exact thing last week, while creating a data bound control. I reflected over the DataBoundControl.GetDataSource method that lead me to the missing FindControl.

It's actually about once or twice a month that I come across .NET internals that I'd liked to be public.

However, the more code you make public, the harder it is to make changes to your library, so I can understand (a bit).

# November 9, 2006 12:36 PM

uday said:

can u send an example using your function findcontrol

# July 19, 2007 7:02 AM

jim said:

I've been looking for this, can you do it using vb?

# August 21, 2007 1:16 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)