C# code snippet: finding all child controls of a given type in a WinForms application

Posted: (EET/GMT+2)

 

Today's blog post is about a simple yet useful C# code snipped related to .NET and Windows Forms application development. Sometimes, you need to find all controls on your form(s) based on their type: for instance to enable or disable all editor controls, change to color of all your grids, and so on.

This isn't difficult, as you can apply basic recursion to the Control.Childs enumeration, and thus loop through all the controls that match a particular type. However, there seems to be plenty of confusion about this on the Internet, as this seems to be a common need, but solutions vary widely, and do not even always work.

Thus, I wanted to share mine, which works great on Windows Forms with .NET 4.5 and Visual Studio 2012. Here's the key method implementation:

private List<T> GetAllControls<T>(Control parent) where T : Control
{
    List<T> controls = new List<T>();
    foreach (Control child in parent.Controls)
    {
        controls.AddRange(GetAllControls<T>(child));
        if (child.GetType() == typeof(T))
        {
            controls.Add(child as T);
        }
    }
    return controls;
}

This method returns a list of controls that match the given type (as specified using the generic T parameter). You can then specify the parent control, from which the child controls are searched for recursively. So if you start from the form level, this method will return all matching controls on that form.

To use this method, you could do so as follows:

private void button1_Click(object sender, EventArgs e)
{
    List<DataGridView> grids = GetAllControls<DataGridView>(this);
    MessageBox.Show(grids.Count + " control(s) found!");
    foreach (DataGridView grid in grids)
    {
        grid.BackgroundColor = Color.Red;
    }
}

Here, a button click event handler on the form calls the GetAllControls method, passing in the type DataGridView. As a result, you get a list of all DataGridViews on the form. After displaying the number of matches found, the code loops through the results, and turns the color of all grids to red.

Enjoy!

Keywords: How to, enumerate all childs based on type; get control children by type; Windows Forms; C#; recursive search