2

I'm currently using an MDI Parent Form and inside of it I will open a Form by clicking in one of the items from the ToolStripMenuItem. I have a code which allows me to open that item only one time instead of opening multiple Forms.

frmRegUser frm = null;

private void createToolStripMenuItem_Click(object sender, EventArgs e)
{
    if (frm == null)
    {
        frm = new frmRegUser();
        frm.MdiParent = this;
    }
    frm.WindowState = System.Windows.Forms.FormWindowState.Maximized;
    frm.Show();
}

So far so good, but then after closing the Form inside of the MDI Parent Form and try to open the same createToolStripMenuItem again it will displays me an error

Cannot access a disposed object. Name of the object: 'frmRegUser'

Then I searched about it and tried to use a code inside of the frmRegUser closing event put this code:

this.Hide();
this.Parent = null;
e.Cancel = true;

It won't open the form again if I want too.

Do you have any ideia how can I solve this problem?

Rekcs
  • 869
  • 1
  • 7
  • 23
  • What does "does not works too" mean? Of course without that `Close` event handler your `frm` gets disposed when it's closed. With that handler you avoid that by _hiding_ the form instead of _closing_. Maybe you should not set the `Parent` to null or reset it when showing again. – René Vogt Aug 31 '17 at 09:31
  • It solved my problem by remove the `this.Parent = null;` line @RenéVogt – Rekcs Aug 31 '17 at 09:34
  • frm.FormClosed += delegate { frm = null; }; – Hans Passant Aug 31 '17 at 09:45
  • I think you dont need any code at all in the closing event. Why hide a form that is closing ? why remove the parent from a form that is closing ? why setting cancel from a form that is closing ? – GuidoG Aug 31 '17 at 10:56

2 Answers2

2

The problem was solved by removing the this.Parent = null; from the frmRegUser_FormClosing event.

Rekcs
  • 869
  • 1
  • 7
  • 23
0

Try this, make sure it's disposed before you initialize:

 if (frm == null || frm.IsDisposed)
Willy David Jr
  • 8,604
  • 6
  • 46
  • 57
  • When I open the form and try to close the app in the ´X´ it will close the `Form` first – Rekcs Aug 31 '17 at 10:05