为什么我的FormClosing事件处理程序抛出一个堆栈溢出异常? [英] Why is my FormClosing event handler throwing a stack overflow exception?
问题描述
如果用户点击关闭/红色X按钮,我想在我的表单上的两个文本框上验证输入。我为Form的FormClosing属性分配了一个事件处理程序,但是当我点击它时,程序进入无限循环,然后抛出堆栈溢出异常。这是我的代码:
I want to validate input on two textboxes on my form if the user clicks the close/"red X" button. I assigned an event handler to the FormClosing property of the Form, but when I click it, the program goes into an infinite loop and then throws the stack overflow exception. Here is my code:
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'文档没有帮助...
What am I doing wrong? As far as I know, if I set the Cancel property to true the form should cancel closing. MS' documentation is no help...
编辑:是不好的做法搭载到 EventArgs e
传递给 this._Cancel
并发送我指定的 e.CloseReason
原来我原来拥有 this.Close()
的原因是因为这个处理程序最初是为表单上的取消按钮编写的(与关闭按钮不同)。我想重用代码,所以我正在考虑在 _Cancel
方法中检查此参数,以确定是否 this.Close()
应该被调用。
Is it bad practice to piggyback onto the EventArgs e
passed in the call to this._Cancel
and send a e.CloseReason
that I specify? The reason why I originally had the this.Close()
is because this handler was originally written for a cancel button on the form (different from the close button). I wanted to reuse the code, so I was thinking of checking this parameter in the _Cancel
method to determine if this.Close()
should be called.
编辑2: Nevermind图我可以检查e.CloseReason是否是UserClosing
EDIT 2: Nevermind figure I can just check if the e.CloseReason is "UserClosing"
推荐答案
阿里你为什么打电话
if (pResult == DialogResult.Yes)
{
this.Close();
return true;
}
else return false;
如果对话框= vbyes根据您的需要返回true或false示例
in case the dialog box = vbyes return true or false as per your need in example
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;
}
}
这篇关于为什么我的FormClosing事件处理程序抛出一个堆栈溢出异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!