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.
Best Answer
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:
Or you can use a for loop:
Or, my new and current favorite, you can use the Reverse() method: