Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

collection was modified enumeration operation may not execute

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();
      }
   }
}
like image 997
Dr Archer Avatar asked Dec 28 '25 07:12

Dr Archer


1 Answers

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.

like image 192
Tim Schmelter Avatar answered Dec 30 '25 22:12

Tim Schmelter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!