Removing items from FormCollection gives error

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi! I implemeted Forms colection described in this link:

http://support.microsoft.com/default.aspx?scid=kb;en-us;815707

I need to loop through the collectionbase and based on form's tag either close the form or do something else.

foreach(Form myForm in Forms)
{
if(myForm.Tag != AppConfig.homePageTitle)
{
myForm.Close();
myForm.Dispose();
}
else
{
// Do something
}
}

I am getting the following error:

"Collection was modified; enumeration operation may not execute."

In good old VB I used a reversed loop. What can I do in C# CollectionBase ?

Many Thanks for your help,

-- Mike
 
Hi Mike,

You cannot modify a collection while it's being enumerated. You might
try this :

Form formToDelete;

do
{
formToDelete = null;
foreach (Form myForm in Forms)
{
if (myForm.Tag != AppConfig.homePageTitle)
{
formToDelete = myForm ;
break;
}
}
if (formToDelete == null) break;
else
{
fc.Remove(formToDelete);
formToDelete.Close();
formToDelete.Dispose();
}
} while(true);

It has the disadvantage of iterating over the collection from the
start after each deletion, but I bet you don't have thousands of forms
in your collection. It should do the trick.

Michel
 
For the sake of completion, here's what I've done:

In the FormCollection class I added the following to be able to address items by index:

public Form this [int index]
{
get
{
return ((Form) List[index]);
}
}


Then I could loop in reverse order:

Form myForm;
for (int i = Forms.Count-1; i>=0; i--)
{
myForm = Forms;

if(myForm.Tag != AppConfig.homePageTitle)
{
myForm.Close();
myForm.Dispose();
}
else
{
//do something
}
}

That did the trick.

Best,

--Mike
 
Back
Top