Hi,
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;
02.
03.private void newToolStripMenuItem_Click(object sender, EventArgs e)
04.{
05. ChildForm child = new ChildForm();
06. child.MdiParent = this;
07. this._myChild = child;
08. child.Show();
09.}
10.
11.private void closeChildToolStripMenuItem_Click(object sender, EventArgs e)
12.{
13. this._myChild.Close();
15.}
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:
this._children.Add(child);
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.