How do I get all controls of a form in Windows Forms?

With recursion…

public static IEnumerable<T> Descendants<T>( this Control control ) where T : class
{
    foreach (Control child in control.Controls) {

        T childOfT = child as T;
        if (childOfT != null) {
            yield return (T)childOfT;
        }

        if (child.HasChildren) {
            foreach (T descendant in Descendants<T>(child)) {
                yield return descendant;
            }
        }
    }
}

You can use the above function like:

var checkBox = (from c in myForm.Descendants<CheckBox>()
                where c.TabIndex == 9
                select c).FirstOrDefault();

That will get the first CheckBox anywhere within the form that has a TabIndex of 9. You can obviously use whatever criteria you want.

If you aren’t a fan of LINQ query syntax, the above could be re-written as:

var checkBox = myForm.Descendants<CheckBox>()
                     .FirstOrDefault(x=>x.TabIndex==9);

Leave a Comment