partialdata
partialdata

Reputation: 113

Checkbox validation

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

Upvotes: 1

Views: 7884

Answers (5)

Dustin Laine
Dustin Laine

Reputation: 38503

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

Upvotes: 0

Dave Anderson
Dave Anderson

Reputation: 12284

Also;

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

Upvotes: 4

DeusAduro
DeusAduro

Reputation: 6066

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

Upvotes: 0

Jay Riggs
Jay Riggs

Reputation: 53595

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

Upvotes: 1

Moayad Mardini
Moayad Mardini

Reputation: 7341

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

Upvotes: 8

Related Questions