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 TrottC# ASP.Net MVC • January 29, 2010
Using C# to Recursively Call FindControl in ASP.Net

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");

About the Author

Tim Trott is a senior software engineer with over 20 years of experience in designing, building, and maintaining software systems across a range of industries. Passionate about clean code, scalable architecture, and continuous learning, he specialises in creating robust solutions that solve real-world problems. He is currently based in Edinburgh, where he develops innovative software and collaborates with teams around the globe.

Related ArticlesThese articles may also be of interest to you

CommentsShare your thoughts in the comments below

My website and its content are free to use without the clutter of adverts, popups, marketing messages or anything else like that. 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 comments. Why not join the discussion!

New comments for this post are currently closed.