collection was modified enumeration operation may not execute

Dr Archer picture Dr Archer · Sep 29, 2013 · Viewed 21.2k times · Source

Okay, so I want to open a new form if it isn't already open. So I check for the form based on the Title or text of the form. Now, so far it works, as in the form opens and if it is already open, it just brings it to the front. But my problem being, that if it isn't open, and I try to create a new instance of it, it throws me the "Collection was modified; Enumeration operation may not execute". And I cannot for the life of me figure out why. Any help is appreciated.

foreach (DataRow iRow in chatcheck.Rows)
{
   FormCollection fc = Application.OpenForms;
   foreach (Form f in fc)
   {
      if (f.Text != ChatReader["Sender"].ToString())
      {

         ChatBox chat = new ChatBox();
         Connection.ConnectionStrings.chatopen = ChatReader["Sender"].ToString();
         chat.Text = Connection.ConnectionStrings.chatopen;
         chat.Show();
         chat.BringToFront();

      }
      else if (f.Text == ChatReader["Sender"].ToString())
      {
              f.BringToFront();
      }
   }
}

Answer

Tim Schmelter picture Tim Schmelter · Sep 29, 2013

Don't use a foreach but a for-loop:

for (int i = 0; i < Application.OpenForms.Count; i++ )
{
    Form f = Application.OpenForms[i];
    if (f.Text != ChatReader["Sender"].ToString())
    {

        //...
        chat.Show();
        chat.BringToFront();
    }
    // ...
}

You canot change the underlying collection of a foreach during enumeration. But that happens if you create a new form and show it there. You add another form to the open-collection.