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;
}
4
  • how do u create those checkboxes? by code? Commented Feb 5, 2015 at 19:49
  • 2
    possible duplicate of Foreach Control in form, how can I do something to all the TextBoxes in my Form? Commented Feb 5, 2015 at 19:51
  • Are you actually naming the controls checkbox# and making them manually in code or is your code generating them? Commented Feb 5, 2015 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. Commented Feb 5, 2015 at 19:54

3 Answers 3

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

At the first code sample, did you mean "checkbox" + counter, true ?
Yes, yes I did. Updated.
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;
    }
}

1 Comment

best Answer to use... also the most compatible way for any project :)
2
void SetAllCheckBoxesState(Boolean isChecked) {

    foreach(Control c in this.Controls) {

        CheckBox cb = c as CheckBox;
        if( cb != null ) cb.Checked = isChecked;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.