Wilfred
Wilfred

Reputation: 29

Close multiple but specified forms (exclude main form)

Please, I want to close multiple but specific forms (excluding main form) from a form with button click event. I have tried the following code but closes all forms (though, excluding main form).

private void button1_Click(object sender, EventArgs e)
{
  FormCollection fc = Application.OpenForms;
      if (fc.Count > 1)
          {
             for (int i = (fc.Count); i > 1; i--)
              {
                 Form SelectedForm = Application.OpenForms[i - 1];
                 SelectedForm.Close();
              }
          }
 }

The forms I would like to close are form2, form3, form5, form7, form12, form16, form17, form18, form19, form21, form22, form22, form23, form24, form25. Would appreciate any valuable assistance. Thank you.

Upvotes: 1

Views: 47

Answers (1)

persian-theme
persian-theme

Reputation: 6638

You can have a parent form and others will inherit from it and those who inherited from this form will be closed when necessary

1. create Parent Form

public partial class MyParentForm : Form
{
   public MyParentForm()
   {
      InitializeComponent();
   }
}

2. Create a test form by inheriting from MyParentForm

public partial class TestForm : MyParentForm
{
   public TestForm()
   {
      InitializeComponent();
   }
}

3. Close forms inherited from MyParentForm

FormCollection fc = Application.OpenForms;
for (int i = (fc.Count); i > 1; i--)
   if (Application.OpenForms[i - 1] is MyParentForm)
      Application.OpenForms[i - 1].Close();

Upvotes: 1

Related Questions