Search code examples
c#foreachdatatablesqldataadapteropenform

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();
      }
   }
}

Solution

  • You can save the information in a foreach loop (e.g. in a List<>), and then open the form, using this information.

                    var myList = new List<something>();
                    foreach (DataRow iRow in chatcheck.Rows)
                    {
                        FormCollection fc = Application.OpenForms;
                        foreach (Form f in fc)
                        {
                            if (f.Text != ChatReader["Sender"].ToString())
                            {
                               myList.Add(...)
                            }
                            else if (f.Text == ChatReader["Sender"].ToString())
                            {
                                f.BringToFront();
                            }
                        }
                    }
    

     

    foreach (var val in myList)
    {
       ChatBox chat = new ChatBox();
       ...
    }