Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collection was modified; enumeration operation may not execute [duplicate]

Tags:

c#

.net

windows

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();
        }
    }
like image 433
user1559618 Avatar asked Dec 16 '22 19:12

user1559618


1 Answers

You can not modify a collection wile enumerating.

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

like image 98
L.B Avatar answered May 21 '23 11:05

L.B