tags:

views:

142

answers:

5

I have 2 check boxes, I want to know how to manage these: if one is checked do that, if the other one is checked do that, if both are checked do both actions.

Also if none are checked and I click on the button to perform the action it should display "Please check one of the options or both."

Thank you for your time

-Summey

+6  A: 
if (!checkBox1.Checked && !checkBox2.Checked)
{
    MessageBox.Show("Please select at least one!");
}
else if (checkBox1.Checked && !checkBox2.Checked)
{
    MessageBox.Show("You selected the first one!");
}
else if (!checkBox1.Checked && checkBox2.Checked)
{
    MessageBox.Show("You selected the second one!");
}
else //Both are checked
{
    MessageBox.Show("You selected both!");
}
Moayad Mardini
ahhh ok ok ok i had that right but i didnt do !checkbox1.checked i was missing the !. Thank you
+1  A: 

I think you'd want something like this:

    private void button1_Click(object sender, EventArgs e) {
        if (checkBox1.Checked) {
            Console.WriteLine("Do checkBox1 thing.");
        }
        if (checkBox2.Checked) {
            Console.WriteLine("Do checkBox2 thing.");
        }
        if (!checkBox1.Checked && !checkBox2.Checked) {
            Console.WriteLine("Do something since neither checkBox1 and checkBox2 are checked.");
        }
    }
Jay Riggs
yeah thats what im after and this should work if they are both checked as well. Thank you
A: 

In the event handler for the button, just verify which buttons are actually checked, ie:

if ( myCheckBox1.Checked && myCheckBox2.Checked )
{
    // Do action for both checked.
}
DeusAduro
+3  A: 

Also;

if(checkBox1.Checked || checkBox2.Checked)
{
  if(checkBox1.Checked) doCheckBox1Stuff();
  if(checkBox2.Checked) doCheckBox2Stuff();
}else {
  MessageBox.Show("Please select at least one option.");
}
Dave Anderson
+1 for conciseness
Skeolan
A: 

Instead of performing the check-box functionality on button click you could use the OnCheckedChanged event of the check-box and set AutoPostBack to true, in ASP.NET. Then you will can execute the check-box actions automatically and perform the data validation on the button click event.

(WinForms)

private void checkbox1_CheckedChanged(object sender, EventArgs e)
{
    //Execute method
}

(ASP.NET)

<asp:CheckBox ID="checkbox" runat="server" OnCheckedChanged="checkbox_OnCheckedChanged" AutoPostBack="true" />

private void checkbox_OnCheckedChanged(object sender, EventArgs e)
{
    //Execute method
}

Button Click Event

protected void button_onclick(object sender, EventArgs e)
{
    if (!checkbox1.Checked || !checkbox2.Checked)
        MessageBox.Show("Error"); 
}
Dustin Laine