Learning never exhausts the mind

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

Usage

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

Example:

Control myControl = FindControlRecursive(PlaceHolder1, "myControl");

 

Did you enjoy this post? Let others know!

If you enjoyed this post, please share it with others. Click one of the social media buttons below to share on Facebook, Twitter, LinkedIn, Pinterest or email to a friend.

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

    Reply
  • 19th December 2011 at 12:00 am

    Good post. This is the one we use.

    <code>
    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;
    }
    </code>

    Reply

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.