为什么我的FormClosing事件处理程序抛出堆栈溢出异常
本文关键字:堆栈 栈溢出 异常 程序 我的 FormClosing 事件处理 为什么 | 更新日期: 2023-09-27 18:00:25
如果用户单击关闭/"红色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的文档没有帮助。。。
EDIT:利用在对this._Cancel
的调用中传递的EventArgs e
并发送我指定的e.CloseReason
是不是一种糟糕的做法?我最初使用this.Close()
的原因是,这个处理程序最初是为表单上的取消按钮(与关闭按钮不同)编写的。我想重用代码,所以我想在_Cancel
方法中检查这个参数,以确定是否应该调用this.Close()
。
编辑2:尽管如此,我只能检查e.CloseReason是否为"UserClosing"
Ali你为什么叫
if (pResult == DialogResult.Yes)
{
this.Close();
return true;
}
else return false;
如果对话框=vbyes根据您在示例中的需要返回true或false
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)
{
//avoid => this.Close();
return true;
}
else return false;
}
else
{
// avoid => this.Close();
return true;
}
}