4

I am getting the error: Collection was modified; enumeration operation may not execute. I am trying to delete all open form objects apart from the current one:

    FormCollection fc = Application.OpenForms;
    foreach (Form form in fc)
    {
        if (form.ToString().Contains("_MainFrom.Form1"))
        {
            // Do nothing
        }
        else
        {
            form.Hide();
            form.Dispose();
        }
    }
user1559618
  • 449
  • 3
  • 6
  • 17

4 Answers4

8

You can not modify a collection wile enumerating.

use foreach (Form form in fc.Cast<Form>().ToList())

L.B
  • 114,136
  • 19
  • 178
  • 224
3

Change

foreach (Form form in fc)

to

foreach (Form form in fc.OfType<Form>().ToList())

This way your are copying to OpenForms collection to a new collection before start removing stuff from the original collection.

Albin Sunnanbo
  • 46,430
  • 8
  • 69
  • 108
1

You cant modify the collection where you are performing enumeration(foreach for example). You should use here others methods such as Remove or use for loop.

seeker
  • 3,255
  • 7
  • 36
  • 68
0

Your question is: "I'm modifying collection of Open forms by closing one of the forms while iterating forms and getting error that I'm modifying collection of Open forms while iterating".

Answer: either don't use foreach iteration OR don't modify collection during iteration. Otherwise they'll find out.

Most common approach is to split such operation into 2 steps:

  • find objects that need to be added/removed from the collection
  • act on resulting collection of objects

In your case:

var toClose = fc.Where(
   form => form.GetType().FullName.Contains("_MainFrom.Form1"));
toClose.ToList().ForEach(form => {
   form.Hide(); form.Dispose(); 
});
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179