Nikolas
Nikolas

Reputation: 188

Collect controls in a form c#

I have a form in which there are some buttons. I'd like put their references in an array.Is it possible with a foreach ?

I want to do this:

    public Form1()
    {
        InitializeComponent();
        Button[] all = new Button[5];
        all[0] = button1;
        all[1] = button2;
        all[3] = button3;
        all[4] = button4;
    }

I've already tried

int i=0;
foreach (Button p in Form1)
{
    all[i]= p;
    i++;
}

But I can't use a foreach on a Form. The same thing if the buttons are in a panel.

What can I do to collect all buttons quickly? Thanks :)

Upvotes: 0

Views: 229

Answers (2)

SLaks
SLaks

Reputation: 887547

You're looking for the Controls collection of your form or container, which contains every control directly in it.

Beware that this will also include non-Buttons; call .OfType<Button>() to filter.

So instead of the foreach you can initialize an array like this:

Button[] all = this.Controls.OfType<Button>().ToArray();

Upvotes: 2

Ren&#233; Vogt
Ren&#233; Vogt

Reputation: 43896

Every Control has a Controls property which is a ControlCollection. You can get all Buttons on a Control (as a Form or a Panel) like this:

foreach(var button in control.Controls.OfType<Button>())
{ ... }

But this will only give you the Buttons that are contained directly by this control. If you want to get all Buttons in your Form on all Panels, GroupBoxs etc, you need to recurse through the Controlslike in this example:

public class Form1 : Form
{
    // ...

    private static IEnumerable<Button> GetAllButtons(Control control)
    {
        return control.Controls.OfType<Button>().Concat(control.Controls.OfType<Control>().SelectMany(GetAllButtons));
    }

    private void DoSomethingWithAllButtons()
    {
        foreach(var button in GetAllButtons(this))
        { // do something with button }
    }
}

Upvotes: 1

Related Questions