0

I have this section of code, which opens a form when the box is checked, then closes it when the box is unchecked:

private void chkDupe_CheckedChanged(object sender, EventArgs e)
{  
    if (chkDupe.Checked == true)
    {
        input = 1;
        CableID_Controller.ShowDuplicateView(Main_Menu, this);
    }
    else if (chkDupe.Checked == false)
    {
        // Close form.
        FormCollection fc = Application.OpenForms;
        foreach (Form frm in fc)
        {
            if (frm is CableID_DuplicateView)
            {
                frm.Close();
            }
        }
    }
}

It opens the form fine, but when I uncheck the box, I get an error:

InvalidOperationException. Collection Was modified; enumeration may not execute.

I know this has something to do with the foreach loop, but I can't think of a way to substitute this for something else. Can anyone provide any suggestions?

Ben
  • 2,433
  • 5
  • 39
  • 69
  • I guess it's because the application tries to remove it from the collection when you close it. You can use an inverted for loop instead (won't mess up your indexes when the deletion occurs). – Pierre-Luc Pineault May 30 '14 at 02:46
  • This question has been answered http://stackoverflow.com/questions/380451/how-do-i-do-i-loop-through-items-in-a-list-box-and-then-remove-that-item and http://stackoverflow.com/questions/1154350/system-invalidoperationexception-collection-was-modified – Jamleck May 30 '14 at 02:56

1 Answers1

1

You are modifying the Application.OpenForms collection while you are iterating it. You need to create a copy before so you iterate over that copy instead of the original collection

var fc = Application.OpenForms.OfType<Form>().ToList();

Also, if you want to Close only CableID_DuplicateView forms, you can use :

var fc = Application.OpenForms.OfType<CableID_DuplicateView>().ToList();

foreach (Form frm in fc)
      frm.Close();

and remove the type check from your loop.

Selman Genç
  • 100,147
  • 13
  • 119
  • 184
  • Perfect! Thanks for this, I'm still a bit of a greenhorn so `var` is not a regular expression for me. – Ben May 30 '14 at 02:54