Collection was modified; enumeration operation may not execute. in foreach()

164 Views Asked by At

I was using a button to output a form in the MDI parent. The frmUser does not have any code or anything, just a plain new form, and this is the only code I have in this form, and the foreach() is having an error of:

InvalidOperationException was unhandled.

Collection was modified; enumeration operation may not execute.

I do not know what is wrong and there are same error question as mine but different circumstances so it does not really help mine. So I wonder what is wrong with the foreach()

The code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MACRO
{
    public partial class frmAdmin : Form
    {
        public frmAdmin()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            bool IsOpen = false;
            foreach (Form f in Application.OpenForms)
            {
                if (f.Text == "frmUsers")
                {
                    IsOpen = true;
                    f.Focus();
                    break;
                }

                if (IsOpen == false)
                {
                    frmUsers users = new frmUsers();
                    users.MdiParent = this;
                    users.Show();
                }
            }
        }
    }
}
0

There are 0 best solutions below