jsls
jsls

Reputation: 261

Condition on checkbox

My questions is quite simple but i don't find any way to do it.

I have several checkboxs, I want to run my void only if 2 of them or more are checked

private void Button1_Click(object sender, EventArgs e)
{

      if (!checkbox1.Checked && !checkbox2.Checked && !checkbox3.Checked &&     !checkbox4.Checked && !checkbox5.Checked)
      {
       Messagebox.Show("Select 2 checkbox");
       return;
      }
       else
      {
       //some action
      }
}

is the trick I use to be sure one checkbox is checked.. But I want to do the same with 2 & more checkboxs.

Ps: I can't use private void checkBox2_CheckedChanged() , I need to use my button1 event.

Upvotes: 1

Views: 92

Answers (1)

René Vogt
René Vogt

Reputation: 43876

You could indeed count the number of checked checkboxes like that:

int count = 0;
if (checkbox1.Checked) count += 1;
if (checkbox2.Checked) count += 1;
if (checkbox3.Checked) count += 1;
if (checkbox4.Checked) count += 1;

if (count < 2)
{
    Messagebox.Show("Select 2 checkbox");    
    return;
}

Or you could put all relevant checkboxes in an array and do this.

CheckBox[] checkboxes = new [] { checkbox1, checkbox2, checkbox3, checkbox4 };
if (checkboxes.Count(cb => cb.Checked) < 2)
{
    Messagebox.Show("Select 2 checkbox");    
    return;
}

The second version easily be extended for more checkboxes by simply adding them to the array.


If even all checkboxes on your form do count, you can use

if(Controls.OfType<CheckBox>().Count(cb => cb.Checked) < 2)
{
    // ....
}

Upvotes: 6

Related Questions