joaogoncalv_es
joaogoncalv_es

Reputation: 309

Re-open child form

I have one Main form and two types of child form

MainForm
ChildFormA - unique
ChildFormB - have multiple forms of this type

I create ChildFormA with:

ChildFormA form1 = new ChildFormA();
form1.MdiParent = this;
form1.Show();

But when i close it with:

form1.Close();

I can't re-open it. I've already read some tips that I can Hide this form instead or closing it. But the X button still closes the form. How to re-open or how to prevent the X button to close and simple hide it?

Upvotes: 3

Views: 2558

Answers (5)

Matthias
Matthias

Reputation: 16209

If you want your child form to remain in its state, you have to subscribe to the FormClosing event and set the Cancel property of the event argument to true.

public ChildForm()
{
    ...
    FormClosing += new FormClosingEventHandler(ChildForm_FormClosing);
}


void ChildForm_FormClosing(object sender, FormClosingEventArgs e)
{
    e.Cancel = true;
    Hide();
}

Keep in mind, that you're form will not get disposed, if you don't add more logic to this.

Otherwise, you can just create a new instance of it.

Upvotes: 9

Luis Filipe
Luis Filipe

Reputation: 8718

You could use the Singleton pattern in for this Form.

http://csharpindepth.com/Articles/General/Singleton.aspx

Look at the 4th approach

Then you would access it using the static instance instead of creating a new one. You still need Matthias Koch solution ,on child Forms

void FormClosing(object sender, FormClosingEventArgs e)
{
    e.Cancel = true;
    Hide();
}

If you need further help with the Singleton pattern, please say so.

Upvotes: 0

Rosmarine Popcorn
Rosmarine Popcorn

Reputation: 10965

You should create a Child Form only Once .

ChildFormA form1 = new ChildFormA();
if(form1 == null)
{
 form1.MdiParent = this;
 form1.Show();
}
else
 form1.Show();

than you should use Matthias Koch solution ,on child Forms

void FormClosing(object sender, FormClosingEventArgs e)
{
    e.Cancel = true;
    Hide();
}

Also Keep ChilFormA as a MDI Class Field ,so you won't lose Ref. to it.

Upvotes: 2

Daniel Kienböck
Daniel Kienböck

Reputation: 105

to prevent the form from closing is described here. I would also advice hide, but maybe it works to set visible to false...

Upvotes: 0

BlackBear
BlackBear

Reputation: 22989

Create a new instance of ChildFormA.

Upvotes: 3

Related Questions