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();
}
}
You can not modify a collection wile enumerating.
use foreach (Form form in fc.Cast<Form>().ToList())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With