GM6
GM6

Reputation: 371

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.

Upvotes: 8

Views: 9143

Answers (3)

Sievajet
Sievajet

Reputation: 3513

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

Upvotes: 24

jophab
jophab

Reputation: 5509

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

Upvotes: 2

mayowa ogundele
mayowa ogundele

Reputation: 463

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

Upvotes: 2

Related Questions