Open the closed form

14,569

Solution 1

When the Close method is called on a Form you cannot call the Show method to make the form visible, because the form's resources have already been released aka Disposed. To hide a form and then make it visible, use the Control.Hide method.

from MSDN

If you want to re-open a form that has been closed, you need to re-create it again the same way you created-it at first:

YourFormType Mainmenu=new YourFormType();
Mainmenu.Show();

Solution 2

I presume that you have a main form, which creates a non-modal child form. Since this child form can be closed independently from the main one, you can have two scenarios:

  1. Child form hasn't been created yet, or it was closed. In this case, create the form and show it.
  2. Child form is already running. In this case, you only need to show it (it may be minimized, and you will want to restore it).

Basically, your main form should keep track of the child form's lifetime, by handling its FormClosed event:

class MainForm : Form
{
    private ChildForm _childForm;

    private void CreateOrShow()
    {
        // if the form is not closed, show it
        if (_childForm == null) 
        {
            _childForm = new ChildForm();

            // attach the handler
            _childForm.FormClosed += ChildFormClosed;
        }

        // show it
        _childForm.Show();
    }

    // when the form closes, detach the handler and clear the field
    void ChildFormClosed(object sender, FormClosedEventArgs args)
    {
        // detach the handler
        _childForm.FormClosed -= ChildFormClosed;

        // let GC collect it (and this way we can tell if it's closed)
        _childForm = null;
    }
}
Share:
14,569
Sephiroth111
Author by

Sephiroth111

Updated on June 04, 2022

Comments

  • Sephiroth111
    Sephiroth111 almost 2 years

    I'm wondering how I can open again the closed form from using this.Close(). Every time I'm trying to open the closed form using Mainmenu.Show(), the exception throws an error "cannot access the disposed object. Object name: Mainmenu".

    How can I open it again?