Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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)

C#
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

C#
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

C#
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

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:
C#
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.
 
Share this answer
 
Use == false for each CheckBox

C#
if (rdo_ApplySelectedCodeToRD.Checked == false && rdo_LeaveRDAlone.Checked == false && rdo_SetRDToZR.Checked == false)
            {
                MessageBox.Show("You must choose a Rest Day Option");
                return;
            }
 
Share this answer
 
C#
if (toc_Blockleave.Checked ==false && toc_Swap.Checked==false && toc_Unavailability.Checked == false )
{

}

use '&&' operator not'&'
 
Share this answer
 
v2

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900