Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing a checkbox Checked event

I have a checkbox on which I want to ask the user if he is sure or I will cancel the operation.

I tried the Click event but it turns out it is only being called after the CheckedChanged event.

I thought I could at least do it "ugly" by asking the user inside the CheckedChanged event but then if he wishes to cancel I need to change the Checked value what raises the event all over again.

Another thing I would prefer to avoid with this solution is that even before the user replies, the tick mark appears in the checkbox.

I'm looking for an event that happens before the CheckedChanged or a way to prevent the CheckedChanged event.

like image 566
GM6 Avatar asked Dec 30 '14 16:12

GM6


3 Answers

Set AutoCheck to false. and handle the Checked state in the Click event.

like image 133
Sievajet Avatar answered Oct 19 '22 14:10

Sievajet


Find the Sample Code. It just removes the event attached to the checkbox and adds it back

private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
  if (checkBox1.Checked)
  {
    checkBox1.CheckedChanged -= checkBox1_CheckedChanged;
    checkBox1.Checked = false;
    checkBox1.CheckedChanged += checkBox1_CheckedChanged;
  }
}
like image 35
mayowa ogundele Avatar answered Oct 19 '22 15:10

mayowa ogundele


Adding up to Sievajet's answer.

The AutoCheck property is set to false to prevent automatic update of checkbox's appearance when it is clicked.

See the official documentation of AutoCheck below

Gets or set a value indicating whether the System.Windows.Forms.CheckBox.Checked or System.Windows.Forms.CheckBox.CheckState values and the System.Windows.Forms.CheckBox's appearance are automatically changed when the System.Windows.Forms.CheckBox is clicked.

Try the ClickEvent Handler Below

private void checkBox_Click(object sender, EventArgs e)
{
   if (checkBox.Checked == false)
   {
     DialogResult result = MessageBox.Show("Confirmation Message", "Confirm", 
                           MessageBoxButtons.OKCancel, MessageBoxIcon.Question);

     if (result == DialogResult.OK)
     {
         checkBox.Checked = true;
     }

   }
   else
   {
     checkBox.Checked = false;
   }
}
like image 22
jophab Avatar answered Oct 19 '22 15:10

jophab