collection was modified enumeration operation may not execute

21,269

Solution 1

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

Solution 2

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.

Share:
21,269
Dr Archer
Author by

Dr Archer

Updated on July 09, 2022

Comments

  • Dr Archer
    Dr Archer almost 2 years

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