c# Delete dialogresult

747 views Asked by At

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

There are 1 answers

2
Steve On BEST ANSWER

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

In this way, the first call seems to go well, but it register the FormClosing event handler a second time. So, when you trigger the action that enters the FormClosing event handler, it is called two times and, in the same call, it will be registered again, and the next time the call is made three times and so on.

The simplest thing to stop this behavior is removing the FormClosing event handler 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();
}

But 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 approach will hit your performances and memory footprint.

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