Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

forms

winforms

I have a Form named A.

A contains lots of different controls, including a main GroupBox. This GroupBox contains lots of tables and others GroupBoxes. I want to find a control which has e.g. tab index 9 in form A, but I don't know which GroupBox contains this control.

How can I do this?

like image 847
Shailesh Avatar asked Apr 29 '10 06:04

Shailesh


3 Answers

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);
like image 110
Josh Avatar answered Nov 14 '22 21:11

Josh


Recursively search through your form's Controls collection.

void FindAndSayHi(Control control)
{
    foreach (Control c in control.Controls)
    {
        Find(c.Controls);
        if (c.TabIndex == 9)
        {
            MessageBox.Show("Hi");
        }
    }
}
like image 43
Ed S. Avatar answered Nov 14 '22 21:11

Ed S.


void iterateControls(Control ctrl)
{
    foreach(Control c in ctrl.Controls)
    {
        iterateControls(c);
    }
}
like image 24
thelost Avatar answered Nov 14 '22 21:11

thelost