[英]C#: How to cancel the close action for a button that's set as the Accept or Cancel button on a form?
I have a button btnOK
on my form, with a DialogResult
property of OK
. 我的
btnOK
上有一个按钮btnOK
,其DialogResult
属性为OK
。 The form's AcceptButton
property is set to btnOK
. 表单的
AcceptButton
属性设置为btnOK
。 So if I click the button, the form closes automatically. 因此,如果单击该按钮,表单将自动关闭。
Now, inside the btnOK_Click()
method, I want to ability to cancel out of the close action, eg if there was an error I want to show a message box and not close the form. 现在,在
btnOK_Click()
方法中,我希望能够取消关闭操作,例如,如果有错误,我想显示一个消息框而不是关闭表单。
How do I do it? 我该怎么做?
在错误添加:
this.DialogResult = DialogResult.None
IMO you just don't have to set DialogResult
property on the button, but set it directly on your form in the btnOK_Click
event: IMO你不必在按钮上设置
DialogResult
属性,而是直接在btnOK_Click
事件中的表单上设置它:
private void btnOK_Click(object sender, EventArgs e)
{
if (yeahLetsClose)
this.DialogResult = DialogResult.OK; // form will close with OK result
// else --> form won't close...
}
BTW, AcceptButton
property is related to ENTER key (when you press it on your form, the AcceptButton
will be pressed) BTW,
AcceptButton
属性与ENTER键相关(当你在表单上按下它时,将按下AcceptButton
)
Add an event handler for the form close event. 为表单关闭事件添加事件处理程序。 The EventArgs parameter should have a Cancel property.
EventArgs参数应具有Cancel属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.