Using C# to Recursively Call FindControl in ASP.Net

Recursively Call FindControl using this function which will not only search on the page, but the component containers as well.

By Tim Trott | C# ASP.Net MVC | January 29, 2010

In ASP.Net I often need to Recursively Call 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 its child controls.

C#
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 into and the name of the control to find.

Example:

C#
Control myControl = FindControlRecursive(PlaceHolder1, "myControl");
Was this article helpful to you?
 

Related ArticlesThese articles may also be of interest to you

CommentsShare your thoughts in the comments below

If you enjoyed reading this article, or it helped you in some way, all I ask in return is you leave a comment below or share this page with your friends. Thank you.

This post has 3 comment(s). Why not join the discussion!

We respect your privacy, and will not make your email public. Learn how your comment data is processed.

  1. AL

    On Wednesday 22nd of March 2023, Alberto Lepore said

    Very effactive way to find controls recursively in asp page, I have adapted your code to my custom needs. It was helpful. Thx

  2. TI

    On Tuesday 5th of June 2012, Tigrou said

    @roy : your function is nice but return type should be T instead of Control, otherwise using templates is pretty useless....

    C#
    private T GetControl<T>(Control Container, string ControlID) where T : Control
  3. RO

    On Monday 19th of December 2011, Roy said

    Good post. This is the one we use.

    C#
    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;
    }