Hi Mike.
You can't use foreach to modify the underlying Collection. Because the override of the Dispose method in the Microsoft example removes the form from the collection, calling Dispose() on the form generates this error.
The simplest solution is to change the override method, removing the line
Forms.Remove(this);
however this will leave a reference to the disposed form in the collection, which you may not want (if you're not going to use the collection again and you don't mind references to the "dead" Forms objects hanging around, this will be sufficient).
To do it "properly" you need to use indexed addressing.
In your forms collection class, add the following method:
public Form this [ int index ] {
get {
return ((Form) List[index]);
}
}
This will allow you to access elements of the collection using the syntax "Forms[index]". So now you can use your reversed loop technique, for example:
for (int i=Forms.Count-1;i>=0;i--)
{
Form myForm=Forms[i];
if(myForm.Tag != AppConfig.homePageTitle)
{
myForm.Close();
myForm.Dispose();
}
else
{
// Do something
}
}
Hope that helps,
CupawnTae
Main Topics
Browse All Topics





by: bhagyeshtPosted on 2004-07-28 at 03:05:36ID: 11654512
when u call Dispose() it removes the form from the forms collection
so dont call dispose just store the index of that and at the end in reverse order ie higher to lower call dispose of the form
Regards,
Bhagyesh