Cannot open and close a form inside of MDI form in C#

503 views Asked by At

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?

2

There are 2 answers

0
Rekcs On

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

1
Willy David Jr On

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

 if (frm == null || frm.IsDisposed)