views:

294

answers:

4

I have a check box and I have subscribed for the CheckedChanged event. The handler does some operations in there. I check and uncheck the checkbox programmatically (ex: chkbx_Name.Checked = true), and the CheckedChanged event gets fired.

I want this event to be fired only when I manually check or uncheck it. Is there any way to avoid firing of this event when i check/uncheck it programmatically?

+1  A: 

No. Those property change events fire whenever the property value changes, regardless of whether this was done by your code, by the control's own code or databinding. It's all the same code path, usually.

What you can do, however, if your event handler resides in the same class as the code that changes the property value, is to introduce a private boolean field in the class which you use as an indicator of whether the current property change is triggered by your code or by the user. After your change you simply reset it. The event handler would then look at the field and decide of whether it should do anything or not:

class Foo : Form {
    private bool checkedProgrammatically = false;

    void someMethod() {
        // ...
        checkedProgrammatically = true;
        checkBox1.Checked = true;
        checkedProgrammatically = false;
        // ...
    }

    private void checkBox1_CheckChanged(object sender, EventArgs e) {
        if (checkedProgrammatically) return;
        // ...
    }
}
Joey
A: 

You can set boolean variable before changing value programiticaly, and check than reset that variable in checkedchanged event

ArsenMkrt
+2  A: 

unsubscribe the event before you set:

check1.CheckChanged -= check1_CheckChanged;

then you can programmatically set the value without the checkbox firing its CheckChanged event:

check1.Checked = true;

then re-subscribe:

check1.CheckChanged += check1_CheckChanged;
Michael Buen
A: 

I'm sorry I can't just comment on Michael Buen's answer due to my being new here (no reputation), but for what it's worth I strongly prefer his solution to Johannes Rössel's for a couple of reasons.

1) the checkedProgrammatically variable is a little too close to global for me. There's nothing to stop another method accidentally setting it to true, causing all your events to stop.

2) you could end up with a lot of variables depending on the number of events you're dealing with. It would be easy to change the wrong one and the results can be difficult to debug.

3) it's more obvious what you're doing when you unsubscribe then resubscribe. All the logic is right there, and you don't need to change your event handlers to exit early depending on certain conditions.

I've used both methods extensively and I find Michael's a lot easier in the long run.

Justin Doyle