C# .NET - closing child form from parent form - Asked By murtaza rampurawala on 05-Sep-11 03:21 AM

respected sir ,
i want my mdi child form to be closed from mdi parent form i am using menu strip item please help me to solve this problem thanks
Reena Jain replied to murtaza rampurawala on 05-Sep-11 03:25 AM

Closing an MDI child form is pretty easy as long at you create it correctly. Below is an example of creating and closing an MDI child form. With my example, I am creating the MDI Child on the click event of aMenu item item titled "New". I am closing the MDI Child on the click event of a menu item titled "Close". Your code will vary depending on how you are triggering these events. You do not need to create menu items like I did, you could use buttons or anything else. These are just what I used for my example:
01.private ChildForm _myChild = null;
03.private void newToolStripMenuItem_Click(object sender, EventArgs e)
05.   ChildForm child = new ChildForm();
06.   child.MdiParent = this;
07.   this._myChild = child;
08.   child.Show();
11.private void closeChildToolStripMenuItem_Click(object sender, EventArgs e)
13.   this._myChild.Close();

1. Create a property in the parent to hold a reference to the MDI child after you create it (see line 1 in the code sample).
2. Create an instance of the child (line 5), set a reference in the child to the parent (line 6), set your reference field (_myChild) to point to the new child form (line 7), and finally, call the Show() method of the child if you wish to show it at this time (Line 8).
3. To close the window, just use your reference (_myChild) to call its Close() method (line 13).

That is all there is to it. If you are create many instances of an MDI form at once, instead of creating a reference like line 1 in the code sample, do the following:
private List<ChildForm> _children = new List<ChildForm>();
Then, when you create the child, simply add it to the list with the following code:
You can close all of the children at once for iterating through the collection and calling the Close() method for each child or to close one particular instance, you can search for the correct instance in the form and close just that instance.
Anoop S replied to murtaza rampurawala on 05-Sep-11 03:27 AM
You can use close method to close child form from parent form
dipa ahuja replied to murtaza rampurawala on 05-Sep-11 03:29 AM
Untitled document
Declare the form globally:
public Form1 f1;
now write this code in the contenxtMenuClick:
private void toolStripMenuItem2_Click(object sender, EventArgs e)
  foreach (Form child in this.MdiChildren)
     if (child.Name == f1.Name)
   f1 = new Form1();
   f1.MdiParent = this;