0

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.

Jackster
  • 17
  • 4

2 Answers2

1

Try following

 for (int i = 0; i < 10; i++)
 {
    ((CheckBox)this.Controls[$"CheckBox{i}"]).Enabled = false;
 }
tchelidze
  • 8,050
  • 1
  • 29
  • 49
  • You probably should use `(CheckBox)this.Controls[...]` instead of `this.Controls[...] as CheckBox` because `as` returns `null` if the Element doesn't exist, as described in [this post](https://stackoverflow.com/a/132467/8649828) – kwyntes Mar 03 '18 at 12:48
0

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)

kwyntes
  • 1,045
  • 10
  • 27