Click here to Skip to main content
15,888,527 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,

I have an MDI container with 1 MenuStrip
C#
New->Form1
     Form2
     Form3

How to close all child forms from an MDI container except the Last Opened Form.

In New->Form1 click I wrote the following code to show Form1:
C#
Form1 fc = new Form1();
fc.TopLevel = false;
fc.MdiParent = this;
fc.Parent = this.splitContainer1.Panel2;
fc.StartPosition = FormStartPosition.CenterParent;
fc.FormBorderStyle = FormBorderStyle.None;
fc.Location = new System.Drawing.Point(0, 70);
fc.ShowInTaskbar = false;
fc.BringToFront();
fc.Show();


Same for Form2 and Form3 clicks.

When I open any one of the menu item, I want to close the remaining two if they are open.

I wrote the following code but it doesn't work for me.
foreach(Form childForm in MdiChildren)
{
   childForm.Close();
}



Regards,
Pawan.
Posted
Updated 12-Jul-10 3:53am
v2

Hello Pawan,

There is a problem with your code in that as soon as you set the MDIParent, the fc immediately becomes an MDI child form. But as soon as you set Panel 2 as the parent, MDIParent is set to null and fc is no longer an MDI child.

MIDL
fc.MdiParent = this;
// At this point fc is an MDI child.
fc.Parent = this.splitContainer1.Panel2;
// At this point MdiParent is null, and fc is no longer an MDI child.


What you need to do is iterate through the forms in the controls collection for Panel2 and close each form as follows.

foreach (Form childForm in this.splitContainer1.Panel2.Controls)
{
  childForm.Close();
}
Form1 fc = new Form1(); 
fc.TopLevel = false; 
fc.Parent = this.splitContainer1.Panel2; 
fc.StartPosition = FormStartPosition.CenterParent; 
fc.FormBorderStyle = FormBorderStyle.None;
fc.BackColor = Color.Green;
fc.Location = new System.Drawing.Point(0, 70); 
fc.ShowInTaskbar = false; 
fc.BringToFront(); 
fc.Show();


I hope this helps you.

Jason.
 
Share this answer
 
Comments
Pawan Kiran 14-Jul-10 0:19am    
Thank u alot.
Hi Jason

U r code helps me alot to solve my issue and Thanks to u.

Regards,
Pawan.
 
Share this answer
 
v2
Hi,
Could you please try by Calling Application.Exit or Simply END (Only in VB)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900