17

Trying to close all forms except for the main menu using

FormCollection formsList = Application.OpenForms;

with a foreach loop and saying,

if (thisForm.Name != "Menu") thisForm.Close();

Which works ok, it skips the menu, and closes the first, but it then errors:

Collection was modified; enumeration operation may not execute

and stops. I have tried a few places, and they all say that this foreach loop is the way to do it, and it is especially annoying as I am not updating my forms list after closing the forms, which I thought might work. The only thing I could think of was to start at the back and work forward using a while.

7 Answers 7

60

If you use foreach to enumerate through a collection, it can't be modified (items added or removed) during the iteration. Try copying references to the forms to another collection, and then remove them by iterating through that collection.

In situations like this, you can use a list or a simple array, such as:

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

foreach (Form f in Application.OpenForms)
    openForms.Add(f);

foreach (Form f in openForms)
{
    if (f.Name != "Menu")
        f.Close();
}

Or you can use a for loop:

for (int i = Application.OpenForms.Count - 1; i >= 0; i--)
{
    if (Application.OpenForms[i].Name != "Menu")
        Application.OpenForms[i].Close();
}

Or, my new and current favorite, you can use the Reverse() method:

foreach (Form f in Application.OpenForms.Reverse())
{
    if (f.Name != "Menu")
        f.Close();
}
2
  • 5
    Note to others - Reverse does not appear to be available in .NET framework 4.
    – John M
    Jan 17, 2015 at 15:18
  • This will not close the form if any Dialog (FileBrowser or MessageBox with YesNo buttons) is open, which requires user interaction. How to close that forms?
    – Sandy
    Oct 18, 2019 at 7:12
4

Here's an even more concise method that uses the same number of lines as your original method:

Form[] forms = Application.OpenForms.Cast<Form>().ToArray();
foreach (Form thisForm in forms)
{
    if (thisForm.Name != "Menu") thisForm.Close();
}

By using Linq's extension method Cast, you can avoid looping through the collection to build an array.

1
  • I used this for my problem ...
    – Ziggler
    Jan 14, 2022 at 20:15
2

That happens when the collection is changed inside a foreach loop that uses it. You are removing an item from formsList inside the loop.

Try this:

for (int i = formsList.Count-1; i > 0; i--)
{
    if (formsList[i].Name != "Menu")
    {
        formsList[i].Close();
    }
}
0
2

To Close all forms :

        for (int i = Application.OpenForms.Count - 1; i >= 0; i--)
        {
            if (Application.OpenForms[i].Name != "Menu")
                Application.OpenForms[i].Close();
        }
1

I know this is old but I needed to perform this same scenario and came up with a elegant and simple way to achieve this as follows

        Form[] formsList = Application.OpenForms.Cast<Form>().Where(x => x.Name == "Form1").ToArray();
        foreach (Form openForm in formsList)
        {                
            openForm.Close();
        }

This will close ALL windows that where opened called Form1

0

As the error states, you can't modify a collection in its foreach.

Instead, you can use a backwards for loop.

1
  • I am trying to close all open forms. When I close first form.. Application.OpenForms FormCollection changes and it throws me exception when it trys to close next form inside for loop
    – Ziggler
    Jan 14, 2022 at 20:04
0

as the form collection is updating for every iteration. When you close a form, it is removed from the form collection. it's like removing a object from memory while it is using .

Not the answer you're looking for? Browse other questions tagged or ask your own question.