Click here to Skip to main content
14,270,034 members
Rate this:
Please Sign up or sign in to vote.
I've got three checkboxes and I need validation so that you can only text one of them. I've got the code so you can only select one of the text boxes (that code looks like this)

private void toc_Blockleave_CheckedChanged(object sender, EventArgs e)
       {
           if (toc_Blockleave.Checked == true)
           {
               toc_Swap.Checked = false; toc_Unavailability.Checked = false;
           }



however I need it so that when btn_Submit is clicked you must have one of the tickboxes selected (you can only select one due to the above code) and it returns a Messagebox.

This is what I tried

if (!(rdo_ApplySelectedCodeToRD.Checked & rdo_LeaveRDAlone.Checked & rdo_SetRDToZR.Checked))
            {
                MessageBox.Show("You must choose a Rest Day Option");
                return;
            }



as well as various other methods but I just can't get it work

if (toc_Blockleave.Checked & toc_Swap.Checked & toc_Unavailability.Checked == false )
            {
                MessageBox.Show("You must choose a Type of Change");
                return;
            }



I tried this and it only worked for one of the boxes and not the toher two.

Thanks :3
Posted
Rate this:
Please Sign up or sign in to vote.

Solution 3

I would use just one event handler for all three checkboxes (btw, you know radio buttons would fit better here, don't you?) and validate using XOR function.

This way:
private void CheckBox_CheckedChanged(object sender, EventArgs e) {
   CheckBox box = (CheckBox)sender;
   if (box != null) {
      if (box.Checked) {
         if (box == toc_Blockleave) {
            toc_Swap.Checked = false;
            toc_Unavailability.Checked = false;
         }
         else if (box == toc_Swap) {
            toc_Blockleave.Checked = false;
            toc_Unavailability.Checked = false;
         }
         else if (box == toc_Unavailability) {
            toc_Blockleave.Checked = false;
            toc_Swap.Checked = false;
         }
      }
   }
   btn_Submit.Enabled = toc_Blockleave.Checked ^ toc_Swap.Checked ^ toc_Unavailability.Checked;
}


Hope this helps.
   
Rate this:
Please Sign up or sign in to vote.

Solution 1

Use == false for each CheckBox

if (rdo_ApplySelectedCodeToRD.Checked == false && rdo_LeaveRDAlone.Checked == false && rdo_SetRDToZR.Checked == false)
            {
                MessageBox.Show("You must choose a Rest Day Option");
                return;
            }
   
Rate this:
Please Sign up or sign in to vote.

Solution 2

if (toc_Blockleave.Checked ==false && toc_Swap.Checked==false && toc_Unavailability.Checked == false )
{

}

use '&&' operator not'&'
   
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100