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.
Set AutoCheck
to false
. and handle the Checked
state in the Click
event.
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;
}
}
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
orSystem.Windows.Forms.CheckBox.CheckState
values and theSystem.Windows.Forms.CheckBox's
appearance are automatically changed when theSystem.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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With