Search code examples
c#winformsmdi

Loop through all MDI children and close all other forms except the current


I am working on a winforms application using c#. I have an MDI container that has a menu on the left and by pushing a button then the appropriate form is visible. If I click for ex 3 times the button which opens Form1 the 6 instances of the form are opened. Thus I thought that I have to write a method that disposes any other Form1 instances. With the following method, I'm looping through the MDI children, but I want some help how to close all other instances except the new one.

  public void DisposeAllButThis(Form form)
    {
        foreach (Form frm in this.MdiChildren)
        {
            if (frm == form)
            {
                frm.Dispose();
                return;
            }
        }
    }

Solution

  • You need to check whether the form is of the same type too:

    public void DisposeAllButThis(Form form)
    {
        foreach (Form frm in this.MdiChildren)
        {
            if (frm.GetType() == form.GetType() 
                && frm != form)
            {
                frm.Dispose();
                frm.Close();
            }
        }
    }
    

    For more information on Close and Dispose see: C# Form.Close vs Form.Dispose