foreach (Form frm in Application.OpenForms)
{
frm.Close();
}
the error occur above code
Collection was modified; enumeration operation may not execute.
foreach (Form frm in Application.OpenForms)
{
frm.Close();
}
the error occur above code
Collection was modified; enumeration operation may not execute.
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
VulpesPosted Mar 26, 2011, 7:35 AM
When you're deleting multiple elements from a collection, the best thing to do is to iterate through the collection backwards which doesn't mess up the indexing of the elements still to be examined:
for(int i = Application.OpenForms.Count - 1; i >=0 ; i--)
{
Application.OpenForms[i].Close();
}
However, if you're simply wanting to close all open forms and the application itself, doing it this way is unnecessary.
All you need to do is close the startup form (normally the one at index 0 in the collection) and all the others close automatically and the application ends.