Števko Marcin Števko Marcin - 2 months ago 22
C# Question

c# Delete dialogresult

How can I delete DialogResult object ?
I am using it as a confirmation for clearing form (removing all controls and reinitializing of controls). The problem is that when I hit yes it recreates the second DialogResult, then third one, then fourth, etc.

SO when user hits yes, I would like to remove this DialogResult. Is there a way?

Code here:

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

Answer Source

When you recall the InitializeComponent you are not only adding your controls ex-novo, but you are also adding all the event handlers present inside the InitializeComponent call INCLUDING the event handler linked to the form itself (the FormClosing event and others if present)

In this way, the first call seems to go well, but the second time the FormClosing is called two times (because you have registered it two times) and the same call register again the FormClosing event handler, so the next time the call is made three times and so on.

The first thing to block this behavior is disabling the FormClosing event before calling InitializeComponent

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

I really don't think that it is a good idea to clear the controls collection and call again the InitializeComponent. Apart from the fact that if you have many event handlers you should remove them all before calling InitializeComponent, this will hit your performances and memory footprint.

Instead I would prepare a list of all dynamically added controls and remove them one by one and prepare also a procedure to reset the fixed controls to their initial value without removing them from the controls collection and readding them again and again.