如何删除DialogResult对象? 我正在使用它作为清除表单的确认(删除所有控件并重新初始化控件)。问题是,当我点击是,它重新创建第二个DialogResult,然后是第三个,然后是第四个,等等。
因此当用户点击是时,我想删除此DialogResult。有办法吗?
代码在这里:
private void GUI_DCP_FormClosing(object sender, FormClosingEventArgs e)
{
var confirmation_text = "If you click 'Yes', all information will be discarded and form reset. If you want to save the input click 'No' and then 'Save'";
DialogResult dialogResult = MessageBox.Show(confirmation_text, "WARNING", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
this.Hide();
e.Cancel = true; // this cancels the close event.
this.Controls.Clear();
this.InitializeComponent();
this.Height = 278;
this.Width = 341;
}
else
{
e.Cancel = true;
}
}
答案 0 :(得分:2)
当您回想起 InitializeComponent 时,您不仅要从头添加控件,还要重新添加所有事件处理程序包含链接到的事件处理程序表单本身(FormClosing事件和其他如果存在)。
通过这种方式,第一次调用似乎进展顺利,但它第二次注册了FormClosing事件处理程序。因此,当您触发进入 FormClosing 事件处理程序的操作时,它会被调用两次,并且在同一次调用中,它将再次注册,并且下次调用三次并且等等。
停止此行为最简单的方法是在调用InitializeComponent
之前删除FormClosing事件处理程序if (dialogResult == DialogResult.Yes)
{
this.Hide();
e.Cancel = true;
// This removes the FormClosing event handler.
// If other event handlers are present you should remove them also.
this.FormClosing -= GUI_DCP_FormClosing;
this.Controls.Clear();
this.InitializeComponent();
this.Height = 278;
this.Width = 341;
// Do not forget to reshow your hidden form now.
this.Show();
}
但我真的不认为清除控件集合并再次调用InitializeComponent是个好主意。
除了事实上,如果你有许多事件处理程序,你应该在调用InitializeComponent之前删除它们,这种方法将达到你的性能和内存占用。
相反,我会准备一个动态添加的控件列表并逐个删除它们。其次,我将编写一个过程来将固定控件重置为其初始值,而不将它们从控件集合中删除并一次又一次地读取它们。