Bilgin Kılıç
Bilgin Kılıç

Reputation: 9129

how to get all the controls on the windows form page

I have a windows forms; and there are several controls on it.
I want to have them in a foreach loop to call each control's Clear() method, to make it clear and re-initiliazed item.

How can I do it?**

When I wath the formpage on debug-mode of Vs 2008, I see the "this" thus I can see all of them inside it..

.net version: 2.0

Upvotes: 0

Views: 2399

Answers (3)

Veldmuis
Veldmuis

Reputation: 4868

You might have controls on controls on controls etc. So it might be a good idea to put Dmitry Erokhin's code in a recursive function:

private void ClearNumberEntries(ControlCollection controls)
{
    foreach (Control ctrl in controls)
    {
        if (ctrl is NumberEntry)
        {
            ((NumberEntry)ctrl).Clear();
        }
        //if you are sure a NumberEntry can never have child controls that could also be of type NumberEntry you can put this in an else in stead
        ClearNumberEntries(ctrl.Controls);
    }
}

Upvotes: 2

Nighil
Nighil

Reputation: 4127

for initializing controls again no need to clear each controls, just clear controls in form and call InitializeComponent()

 private void InitializeControls()
        {
            this.Controls.Clear();
            InitializeComponent();
        }

Upvotes: 0

Dmitrii Erokhin
Dmitrii Erokhin

Reputation: 1347

You could iterate through controls like this:

foreach (Control ctrl in this.Controls)
{
    if (ctrl is NumberEntry)
    {
        ((NumberEntry)ctrl).Clear();
    }
}

Upvotes: 1

Related Questions