Triak
Triak

Reputation: 135

Control C# checkbox using variable

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;
}

Upvotes: 1

Views: 2764

Answers (3)

Metro Smurf
Metro Smurf

Reputation: 38335

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;
}

Upvotes: 5

Dai
Dai

Reputation: 155055

void SetAllCheckBoxesState(Boolean isChecked) {

    foreach(Control c in this.Controls) {

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

Upvotes: 2

JeremyK
JeremyK

Reputation: 1103

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;
    }
}

Upvotes: 4

Related Questions