Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

winforms

mdi

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;
            }
        }
    }
like image 600
user1292656 Avatar asked Oct 15 '25 16:10

user1292656


2 Answers

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

like image 125
Emond Avatar answered Oct 18 '25 09:10

Emond


public void DisposeAllButThis(Form form)
{
    foreach (Form frm in this.MdiChildren)
    {
        if (frm != form)
        {
            frm.Dispose();   
            frm.Close();          
        }
    }
    return;
}
like image 24
Andriy Vandych Avatar answered Oct 18 '25 08:10

Andriy Vandych