Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cancel any event in winforms?

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#

like image 848
Shantanu Gupta Avatar asked Apr 20 '10 05:04

Shantanu Gupta


People also ask

How do I stop a form from closing?

To cancel the closure of a form, set the Cancel property of the CancelEventArgs passed to your event handler to true .

What is e cancel in C#?

After you set e. Cancel to true, the event caller (the form) will check that value and decide to process the event if it is true (or not to process it if it false). In your case, if you set the value to false, then the base method OnClosing will not close the form.

Is WinForms outdated?

As we mentioned above, WinForms is still available but the status of “maintenance mode” likely means it has no long term future. As time passed by, especially in the last 5-10 years, new tools continued to mature and rise in popularity, and each one of them offered many powerful features.


1 Answers

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.

like image 58
Marc Gravell Avatar answered Oct 01 '22 14:10

Marc Gravell