Recursively finding an ASP.NET control with a specific ID

I wrote a short recursive method for locating specific controls while having no idea of where they are in a nested structure; actually, I added one dynamically and needed to find it again. This will return the first control matching the ID below the supplied root control, if it can find one of course.

FindControlRecursively method

private static Control FindControlRecursively(Control root, string controlId)
{
    if (controlId.Equals(root.ID))
    {
        return root;
    }
    return (from Control control in root.Controls
            select FindControlRecursively(control, controlId))
        .FirstOrDefault(c => c != null);
}

Usage

protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
    var myLabel = FindControlRecursively(Page, "MyLabelID") as Label;
}

As Page is also a Control it may be passed along as root parameter. If you are looking for controls of a specific type, this post might help you out.

Leave a Reply