C# 在离开accept_button事件之前进行验证
如果这是一个愚蠢的问题,请原谅,但我是这里的初学者。
我有一个简单的自定义对话框,带有两个按钮:接受和取消。 Accept按钮是表单的acceptButton。
我想对 Accept_Click 事件进行一些验证,并决定是否可以关闭对话框,但每次离开此方法时,对话框都会自动关闭并返回 Ok。
我该怎么做才能阻止对话框自行关闭? 或者我必须以其他方式做事?
谢谢
Excuse me if this is a silly question but i'm a beginer here.
I have a simply custom dialog with two buttons: Accept and Cancel. The Accept button is the acceptButton of the form.
I want to do some validations on the Accept_Click event and decide if i can close the dialog or not, but everytime it leaves this method, the dialog automatically closes itself and returns Ok.
What can I do to stop the dialog from closing itself? or i have to do things in some other way?
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我将有一个表单级别变量(称之为 _
vetoClosing
) 在接受按钮的 Click 事件中,我将运行验证并根据该变量设置变量:然后在 FormClosing 事件中,我将取消关闭,如果_vetoClosing 为 true
关闭“接受”按钮不是最佳选择,因为您会失去 Enter to Press 功能。
I would have a form level variable (call it _
vetoClosing
) In the accept button's Click event, I would run validation and set the variable based on that:Then in the FormClosing event, I would cancel close if _vetoClosing is true
Turning Accept button off is suboptimal because you loose the Enter to Press functionality.
更简洁的解决方案是将 DialogResult 设置为 None:
A cleaner solution would be to set DialogResult to None:
我将在控件更改时进行验证,并且仅在整个表单有效时才启用“接受”按钮。
这将允许您将按钮保留为默认按钮 (AcceptButton),但可以防止这种情况发生。
I would validate as the controls change, and only enable the Accept button if the whole form is valid.
This would allow you to keep your button as the default button (AcceptButton), but prevent this from occurring.
表单上的 AcceptButton 或 CancelButton 是否设置为该按钮? 如果是这样,请尝试取消设置并在想要关闭对话框时在处理程序中手动设置 DialogResult。
Is the AcceptButton or CancelButton on the form set to that button? If so, try unsetting it and manually setting DialogResult in your handler when you want to close the dialog.