1

I have this code:

// code above
 checkBox1.Checked = false;
 checkBox2.Checked = false;
 checkBox3.Checked = false;
 checkBox4.Checked = false;
 checkBox5.Checked = false;
 checkBox6.Checked = false;
 checkBox7.Checked = false;
 checkBox8.Checked = false;
 checkBox9.Checked = false;
//code below

I have 320 checkBoxes to set cleared/false.
How do I control checkBox(variable)?
I would like to do the following:

for (int counter=1; counter<321; counter++)
{
 checkBox***Put counter Variable Here***.Checked = false;
}
Triak
  • 135
  • 1
  • 8
  • how do u create those checkboxes? by code? – Vinicius Kamakura Feb 05 '15 at 19:49
  • 2
    possible duplicate of [Foreach Control in form, how can I do something to all the TextBoxes in my Form?](http://stackoverflow.com/questions/1499049/foreach-control-in-form-how-can-i-do-something-to-all-the-textboxes-in-my-form) – Black Frog Feb 05 '15 at 19:51
  • Are you actually naming the controls checkbox# and making them manually in code or is your code generating them? – JNYRanger Feb 05 '15 at 19:52
  • I set a checkbox in the design menu, then the VS gives its name. I am writing first code in my question by hand. – Triak Feb 05 '15 at 19:54

3 Answers3

5

If all the checkboxes are incremental, then you can use the Control.ControlCollection.Find Method.

for (int counter=1; counter<321; counter++)
{
   var ctrl = this.Controls.Find("checkbox" + counter, true).FirstOrDefault() as CheckBox;
   if (ctrl != null)
   {
      ctrl.Checked = false;
   }
}

If you just want to set every checkbox, then filter the Controls collection:

var checkBoxes = this.Controls.OfType<CheckBox>();
foreach (CheckBox cbx in checkBoxes)
{
    cbx.Checked = false;
}
Metro Smurf
  • 37,266
  • 20
  • 108
  • 140
4

You can loop through all of the controls on the form and check for check boxes.

foreach (Control ctrl in Controls)
{
    if (ctrl is CheckBox)
    {
        ((CheckBox)ctrl).Checked = false;
    }
}
JeremyK
  • 1,075
  • 1
  • 22
  • 45
2
void SetAllCheckBoxesState(Boolean isChecked) {

    foreach(Control c in this.Controls) {

        CheckBox cb = c as CheckBox;
        if( cb != null ) cb.Checked = isChecked;
    }
}
Dai
  • 141,631
  • 28
  • 261
  • 374