【问题标题】:Why is my FormClosing event handler throwing a stack overflow exception?为什么我的 FormClosing 事件处理程序会引发堆栈溢出异常?
【发布时间】: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._CancelEventArgs e 并发送我指定的e.CloseReason 是不好的做法吗?我最初有this.Close() 的原因是因为这个处理程序最初是为表单上的取消按钮(不同于关闭按钮)编写的。我想重用代码,所以我想在_Cancel方法中检查这个参数,以确定是否应该调用this.Close()

编辑 2: 没关系,我可以检查 e.CloseReason 是否为“UserClosing”

【问题讨论】:

  • 不要在 FormClosing 事件处理程序中调用 Close()。

标签: c# .net winforms event-handling stack-overflow


【解决方案1】:

阿里你为什么打电话

 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;
 }

}

【讨论】:

  • 谢谢,这是票(连同上面的 Hans Passant 的评论)。不敢相信我错过了......一旦我能够接受这个答案(所以由于某种原因目前不允许我接受)​​。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-01-13
  • 1970-01-01
  • 2013-06-11
  • 1970-01-01
  • 2021-06-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多