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
  • 399
  • 3
  • 5
  • 16

4 Answers4

8

You can not modify a collection wile enumerating.

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

L.B
  • 110,417
  • 19
  • 170
  • 215
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
  • 45,452
  • 8
  • 67
  • 106
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,135
  • 7
  • 34
  • 66
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
  • 96,782
  • 12
  • 124
  • 169