Hi All,
I am working on application with a MDI Form, i want to close all opened child forms while opening any of the child form.

How can i do that??

Regards,
Vidya

Recommended Answers

All 2 Replies

Try this:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace daniweb.mdi
{
  public partial class frmMain : Form
  {
    public frmMain()
    {
      InitializeComponent();
    }

    private Form OpenForm(Type t)
    {
      if (!t.IsSubclassOf(typeof(Form)) && !(t == typeof(Form)))
        throw new ArgumentException("Type is not a form", "t");

      List<Form> lst = new List<Form>();

      try
      {
        for (int i1 = 0; i1 < Application.OpenForms.Count; i1++)
        {
          Form f = Application.OpenForms[i1];
          if (f.IsMdiChild)
            lst.Add(f);
        }
      }
      catch (IndexOutOfRangeException)
      {
        //This can change if they close/open a form while code is running. Just throw it away
      }

      while (lst.Count > 0)
      {
        Form f = lst[0];
        f.Close();
        f.Dispose();
        lst.RemoveAt(0);
      }

      Form result = (Form)Activator.CreateInstance(t);
      result.MdiParent = this;
      result.Show();
      return result;
    }

    private void openForm1ToolStripMenuItem_Click(object sender, EventArgs e)
    {
      frmMdi1 frm = (frmMdi1)OpenForm(typeof(frmMdi1));
      frm.Text = "abc";
    }

    private void openForm2ToolStripMenuItem_Click(object sender, EventArgs e)
    {
      frmMdi2 frm = (frmMdi2)OpenForm(typeof(frmMdi2));
      frm.Text = "123";
    }
  }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.