Open the closed form
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.
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:
- Child form hasn't been created yet, or it was closed. In this case, create the form and show it.
- 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;
}
}
Sephiroth111
Updated on June 04, 2022Comments
-
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?