OWE
OWE

Reputation: 23

How can I use some controls on the form such an array of them

I have about 20 checkboxes on the form. How can I name them to use them later in a for loop for example? A thing such an array checkBox[i].

Regards

Upvotes: 2

Views: 61

Answers (4)

ispiro
ispiro

Reputation: 27633

    CheckBox[] MyCheckBoxes = new CheckBox[20];
    for (int i = 0; i < 20; i++)
    {
        MyCheckBoxes[i] = new CheckBox();
        MyCheckBoxes[i].Checked = true;
        //etc
    }

Upvotes: 0

Jon
Jon

Reputation: 437336

I am assuming that the controls are being created as part of InitializeComponent(), i.e. it's done by designer code.

The straightforward approach would be to do this after InitializeComponent is called:

var checkboxes = new[]
{
    checkBox1, // these are the names you have given
    checkBox2, // to the checkboxes in the designer
    checkBox3,
};

A better way would be to use LINQ to put all checkboxes in an array:

var checkboxes = this.Controls.OfType<CheckBox>().ToArray();

However, this will not work recursively and you may have to filter some checkboxes out of the collection if you don't want all of them to be in the array.

Upvotes: 1

nik.shornikov
nik.shornikov

Reputation: 1935

Check out container controls, they automatically create collections of the controls you place within them in design view.

Upvotes: 0

Related Questions