Learning never exhausts the mind

Published on by

In ASP.Net I often need to use the recursively use 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 it's 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;


You need to pass in two parameters, a reference to a control to look in and the name of the control to find.


Control myControl = FindControlRecursive(PlaceHolder1, "myControl");
2 thoughts on “Using C# to Recursively Call FindControl in ASP.Net
  • 5th June 2012 at 12:00 am

    @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

  • 19th December 2011 at 12:00 am

    Good post. This is the one we use.

    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)

    return result;


Leave a Reply

Fields marked with * are mandatory.

We respect your privacy, and will not make your email public. Hashed email address may be checked against Gravatar service to retrieve avatars. This site uses Akismet to reduce spam. Learn how your comment data is processed.