1

my code is:

    private void studentToolStripMenuItem_Click(object sender, EventArgs e)
    {

        foreach (Form frm in Application.OpenForms)
        {
            if (frm.Text == "student")
            {
                frm.Activate();
            }
            else
            {
                studetn obj = new studetn();
                obj.MdiParent = this;
                obj.Dock = DockStyle.Fill;
                obj.Show();
            }
        }                                                                     
    }
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364

1 Answers1

2

Show() command modifies the Application.OpenForms collection which you are enumerating. It is not allowed. You should create and show the new form outside of the foreach loop:

private void studentToolStripMenuItem_Click(object sender, EventArgs e)
{
    // Find the student form
    Form frmStudent = null;
    foreach (Form frm in Application.OpenForms)
    {
        if (frm.Text == "student")
        {
            frmStudent = frm;
            break;
        }
    }                                                                     
    // if found - activate, if not found - create
    if(frmStudent!=null)
    {
        frmStudent.Activate();
    }
    else
    {
        studetn obj = new studetn();
        obj.MdiParent = this;
        obj.Dock = DockStyle.Fill;
        obj.Show();
    }
}
SashaDu
  • 376
  • 1
  • 5