Search code examples
c#foreachinvalidoperationexception

Close a form on CheckChanged event


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?


Solution

  • 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.