【发布时间】:2014-04-27 01:18:13
【问题描述】:
如果用户单击关闭/“红色 X”按钮,我想验证表单上两个文本框的输入。我为 Form 的 FormClosing 属性分配了一个事件处理程序,但是当我单击它时,程序进入无限循环,然后抛出堆栈溢出异常。这是我的代码:
private bool _Cancel(object sender, EventArgs e)
{
if (((this.textboxFirstName.Text != null) && (this.textboxFirstName.Text != string.Empty))
|| ((this.textboxLastName.Text != null) && (this.textboxLastName.Text != string.Empty)))
{
DialogResult pResult = MessageBox.Show("Do you want to cancel adding this driver?", "Warning", MessageBoxButtons.YesNo);
if (pResult == DialogResult.Yes)
{
this.Close();
return true;
}
else return false;
}
else
{
this.Close();
return true;
}
}
private void AddDriver_Window_FormClosing(object sender, FormClosingEventArgs e)
{
if (!this._Cancel(sender, e))
e.Cancel = true;
}
我做错了什么?据我所知,如果我将 Cancel 属性设置为 true,则表单应该取消关闭。 MS 的文档没有帮助...
编辑: 捎带传递给this._Cancel 的EventArgs e 并发送我指定的e.CloseReason 是不好的做法吗?我最初有this.Close() 的原因是因为这个处理程序最初是为表单上的取消按钮(不同于关闭按钮)编写的。我想重用代码,所以我想在_Cancel方法中检查这个参数,以确定是否应该调用this.Close()。
编辑 2: 没关系,我可以检查 e.CloseReason 是否为“UserClosing”
【问题讨论】:
-
不要在 FormClosing 事件处理程序中调用 Close()。
标签: c# .net winforms event-handling stack-overflow