1

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

5 Answers 5

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

1 Comment

ahhh ok ok ok i had that right but i didnt do !checkbox1.checked i was missing the !. Thank you
4

Also;

if(checkBox1.Checked || checkBox2.Checked)
{
  if(checkBox1.Checked) doCheckBox1Stuff();
  if(checkBox2.Checked) doCheckBox2Stuff();
}else {
  MessageBox.Show("Please select at least one option.");
}

Comments

1

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.");
        }
    }

1 Comment

yeah thats what im after and this should work if they are both checked as well. Thank you
0

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

Comments

0

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

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.