0

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();
                }
            }
        }
    }
}
Richard Johnson
  • 309
  • 4
  • 17
  • Which operation trigger this error? it should be part of stack trace. – Pribina Apr 06 '22 at 10:10
  • Probably f.Focus? – Clemens Apr 06 '22 at 10:11
  • 3
    The logic is broken anyway - the code that creates a new form and shows it (and thus changes the set of `OpenForms`) shouldn't be in the loop at all - it should be *after* the loop if it turned out that *none* of the forms were `frmUsers`. So fix the actual logic and the error caused by opening forms at the wrong time will go away also. – Damien_The_Unbeliever Apr 06 '22 at 10:12
  • 1
    (Of course one might also observe that you can access forms by name from the `FormCollection` that `OpenForms` returns and so the loop isn't required at all) – Damien_The_Unbeliever Apr 06 '22 at 10:18
  • 1
    I'm sure the other questions you found *would* help here. By showing a form within the loop, the collection `OpenForms` is modified (as a new one is added). However, as above, this logic is almost certainly incorrect. – Charles Mager Apr 06 '22 at 11:22
  • @CharlesMager what should I do? – Richard Johnson Apr 06 '22 at 12:15
  • 1
    As @Damien_The_Unbeliever suggests, the form should be opened *after* the loop has completed and you know none of the open forms are the one you're looking for. At the moment you open it if the *first* one doesn't match. – Charles Mager Apr 06 '22 at 12:19
  • ohh thanks sorry im just a beginner at this. Thanks for the help – Richard Johnson Apr 06 '22 at 12:22

0 Answers0