Jackster
Jackster

Reputation: 17

Accessing checkboxes with variables

I have asked this question previously but for VB.NET here:

Accessing buttons names using variables

Now I want to do the same but in C# and with CheckBoxes so for example, if I have 31 check boxes labeled "CheckBox1...CheckBox31" I could do :

for (int i = 0; i < 10; i++)
{
    (CheckBox + i).Enabled = false;
}

Thanks for any suggestions.

Upvotes: 0

Views: 65

Answers (2)

kwyntes
kwyntes

Reputation: 1302

You can try creating a List<CheckBox> or an array of all checkboxes:

for (int i = 0; i < checkbox_array.Length; i++) {
    checkbox_array[i].Enabled = false;
}

EDIT: I might be a bit late, but if you put all CheckBoxes in a GroupBox (wich I really recommend doing if you have soo many checkboxes), you can just loop trough all the controls in that groupbox like this:

foreach (CheckBox cbx in gbxCheckBoxes.Controls) {
    cbx.Enabled = true;
}

or like this: (if you only need to enable them)

gbxCheckBoxes.Enabled = false;

(gbxCheckBoxes is the GroupBox I was talking about)

Upvotes: 0

tchelidze
tchelidze

Reputation: 8318

Try following

 for (int i = 0; i < 10; i++)
 {
    ((CheckBox)this.Controls[$"CheckBox{i}"]).Enabled = false;
 }

Upvotes: 1

Related Questions