0
votes

I have three forms in my application. Form1, Form2, and Form3.

Form1 opens Form2 and they are both open. This is OK. I want this to happen.

Form2 has a button that opens Form3. Again, this is desired behavior.

Form3 has two buttons... One that closes Form3 and goes back to Form1 and Form2 being open. I can do this one.

The problem is the second button on Form3... I need that button to close Form3 and Form2 so that only Form1 is now open.

Any ideas on how to close multiple forms at a time without closing the application?

2
Make a Boolean property in Form3, attach to Form 3's FormClosing event in Form 2. Check the property close Form2 if it is true, else do nothing and let Form3 close. - Mark Hall
Hmya, why is there a button? What's supposed to happen when the user uses the normal way to close a window? Why can't you use form3's FormClosed event in form2? Why haven't you shown at least an attempt at making it work so we don't have to prompt you for info like this? - Hans Passant

2 Answers

0
votes

Build a list of all Forms in the Application.OpenForms collection that are not of type Form1; then close them:

    private void btnCloseAllExceptForm1_Click(object sender, EventArgs e)
    {
        List<Form> formsToClose = new List<Form>();
        foreach(Form frm in Application.OpenForms)
        {
            if (!(frm is Form1))
            {
                formsToClose.Add(frm);
            }
        }
        foreach(Form frm in formsToClose)
        {
            frm.Close();
        }
    }
0
votes

Alternatively, you can have a local reference to the Form2 that opened the specific Form3 and pass it in Form3's constructor:

//references the Form2 that opens me (this is Form3)
private Form2 MyForm2Instance;

//you can add this in your existing Form3's constructor, or create a new one
public Form3(Form2 frm2)
{
    InitializeComponent();
    MyForm2Instance = frm2;
}

Then in your Form3's button you can have:

private void button1_Click(object sender, EventArgs e)
{
    //this will close only the Form2 that opened this Form3
    //and it will also close this Form3
    MyForm2Instance.Close();
    this.Close();
}

Now all you need is to change the way you open your Form3, by using the new constructor from Form2:

Form3 frm3 = new Form3(this);
frm3.Show();