views:

127

answers:

2

I want to cancel an event from within that function scope.

Eg. I pressed button click event and on false validation, I want to cancel this event. Likewise i want to cancel other events also.

How can i do this in C#

+3  A: 

It depends on the scenario; in most cases: rather than cancel the event, just do nothing, for example:

private void SaveDataClicked(object sender, EventArgs args) {
    if(!ValidateData()) return;
    // [snip: code that does stuff]
}

or:

private void SaveDataClicked(object sender, EventArgs args) {
    if(ValidateData()) {
        // [snip: code that does stuff]
    }
}

There are some events that expose a CancelEventArgs (or similar), allowing to to cancel some external behaviour via the args - form-closing being the most obvious example (set e.Cancel = true;).

Note that in this scenario I would not have an automatic dialog-result on the button; apply that manually when (if) the handler completes successfully.

Marc Gravell
@Marc: Thx for providing usefull knowledge. I worked out for both scenario.
Shantanu Gupta
A: 

Event subscription is done using += operator:

Button1.Click += button1_Click;

To cancel this subscription, use -= operator:

Button1.Click -= button1_Click;

Alex Farber
-1: He's not trying to cancel a subscription - he's trying to cancel an event in-progress.
John Saunders
I didn't think that the question is so simple, thank you, mommy, for your great note.
Alex Farber