Click here to Skip to main content
15,897,518 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i want to avoid More than one child windows form open in my application in mdi from.
i make a component for that it has method to do this when i calling a method the runtime error occur. error is as
'Collection was modified enumeration operation may not execute.'
the code is as

C#
if (checkopen0 == 1)
          {
              MessageBox.Show("Already Open");
              return;
          }

              closeForm1.CloseAllOpenForm(this);



          StudentMaster frm = new StudentMaster();
          frm.MdiParent = this;
          frm.Show();
          checkopen0 = 1;


the code for component class is as


MIDL
public partial class CloseForm : Component
{
    public CloseForm()
    {
        InitializeComponent();
    }

    public CloseForm(IContainer container)
    {
        container.Add(this);

        InitializeComponent();
    }
    public void CloseAllOpenForm(Form CurForm)
    {
        lock (CurForm)
        {
            foreach (Form frm in System.Windows.Forms.Application.OpenForms)
            {

                if (!(CurForm.Equals(frm)))
                {
                    frm.Close();
                }
            }
        }

    }
}



plz help me to solve this error
and sory for poor english.
thanks in advance.
Posted

1 solution

You cannot alter an enumeration while iterating over it.

You can create a temporary collection of matching forms and then iterate over that collection and close them:

C#
public void CloseAllOpenForm( Form currentForm )
{
    // temp list
    var list = new List<Form>();

    // fill list
    foreach ( Form form in Application.OpenForms )
        if ( !currentForm.Equals( form ) )
            list.Add( form );

    // close selected forms
    foreach ( Form form in list )
        form.Close();
}


Nick
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900