Thursday, February 10, 2011

How to find nested controls in ASP.Net Webforms

I made a little helper class to find all controls of a certain type on a page or within any control that can contain other controls.

Please use it with care since it could be quite heavy on a page with thousands of control. Do not pass the entire page unless absolutely necessary.

/// <summary>
/// Finds all controls of type T stores them in FoundControls
/// </summary>
/// <typeparam name="T"></typeparam>
private class ControlFinder<T> where T : Control 
{
    private readonly List<T> _foundControls = new List<T>();
    public IEnumerable<T> FoundControls
    {
        get { return _foundControls; }
    }    
 
    public void FindChildControlsRecursive(Control control)
    {
        foreach (Control childControl in control.Controls)
        {
            if (childControl.GetType() == typeof(T))
            {
                _foundControls.Add((T)childControl);
            }
            else
            {
                FindChildControlsRecursive(childControl);
            }
        }
    }
}

No comments: