Search code examples
c#mdichildmdiparent

how to call MdiChild from MDIParent form


I create a new MdiChild from MainForm using this method:

AdminLogInForm adminForm;
 private void LogInAsAdminMenuItem_Click(object sender, EventArgs e)
    {
        if (adminForm == null)
        {
            adminForm = new AdminLogInForm();
            adminForm.MdiParent = this;
            adminForm.Show();
            adminForm.Dock = DockStyle.Fill;
            adminForm.BringToFront();
            LogInAsAdminMenuItem.Enabled = false;              
        }
        else
        {
            adminForm.Activate();
            adminForm.BringToFront();
        }
    }

Why when i close my child, using in chld form "this.close()" using that method i cant open it anymore?

there i call close();

        private void cancelLogInButton_Click(object sender, EventArgs e)
    {
        this.MdiParent.Activate();            
        if(this.MdiParent!=null)
        ((MainForm)this.MdiParent).LogInAsAdminMenuItem.Enabled = true;
        this.Close();
    }

by the way to make work that I asked before I hed to plase this.Close(); after all statements .


Solution

  • By closing the form you are not making adminForm instance to null (Which is what your if condition will check when you try to open it next time.)

    On diposal of your form make adminForm = null and then your if condition will work next time.

    private void LogInAsAdminMenuItem_Click(object sender, EventArgs e)
        {
            if (adminForm == null)
            {
                adminForm = new AdminLogInForm(this);
                adminForm.Disposed += new EventHandler(adminForm_Disposed); //Add Disposed EventHandler
                adminForm.MdiParent = this;
                adminForm.Show();
                adminForm.Dock = DockStyle.Fill;
                adminForm.BringToFront();
                LogInAsAdminMenuItem.Enabled = false;              
            }
            else
            {
                adminForm.Activate();
                adminForm.BringToFront();
            }
        }
    
        void adminForm_Disposed(object sender, EventArgs e)
        {
            adminForm = null;
        }