How to cancel any event in winforms?

痴心易碎 提交于 2019-12-19 17:38:13

问题


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#


回答1:


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.




回答2:


private void SaveDataClicked(object sender, EventArgs args)
 {
   args.cancel = true;
 }


来源:https://stackoverflow.com/questions/2672890/how-to-cancel-any-event-in-winforms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!