Recursive FindControl Extension Method

When working with templated controls it’s quite common to need a recursive FindControl method to navigate down through the control hierarchy to find the control you want.

Here is a simple extension method I wrote for Control to do this:


public static Control FindControl(this Control ctrl, string id, bool recursive)
{
    if (recursive)
    {
        foreach (Control child in ctrl.Controls)
        {
            if (child.ID != null && child.ID.Equals(id))
            {
                return child;
            }

            if (child.Controls.Count > 0)
            {
                Control found = FindControl(child, id, true);
                if (found != null)
                {
                    return found;
                }
            }
        }
    }
    else
    {
        return ctrl.FindControl(id);
    }

    return null;
}

Posted on by Joe in ASP.NET, C#

Add a Comment