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.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
VulpesRank #55 · 29.2K reputationPosted Mar 26, 2011, 3:35 AM EDT
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.