Iteration over dynamically added nested controls in C#

A generic function to use for any control type in any container at any levels:

public static List<T> FindControls<T>(Control container, bool dig) where T : Control
    List<T> retVal = new List<T>();
    foreach (Control item in container.Controls)
        if (item is T)
        if (dig && item.Controls.Count > 0)
            retVal.AddRange(FindControls<T>(item, dig));
    return retVal;

The dig variable controls whether or not to iterate through child container controls.
For example if you want to find all PictureBox controls starting from your first GroupBox (gbFirst),
you must call

FindControls<PictureBox>(gbFirst, true);

If set dig to false, only controls in the input cotainer will be enumerated.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s