views:

147

answers:

3

"Collection was modified; enumeration operation may not execute." appears to be a common error with foreach loops, but I can't figure mine out. I have two classes of forms. One is begun on startup, and a button creates new instances of the second form, and displays them. When I close the secondary forms, I get an InvalidOperationException.

FirstForm.cs

public partial class FirstForm : Form
{
    SecondForm frmSecond;
    ...
    private void button1_Click(object sender, EventArgs e)
    {
        frmSecond= new SecondForm ();
        frmSecond.Show();
    }
}

SecondForm.designer.cs

partial class SecondForm
{
    ...
    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing); // InvalidOperationException thrown here.
    }
}
A: 

Can it be that it calls Dispose recursively? Can you have a look at the call stack when the exception occurs?

If this is the case, the broken collection would be the collection of controls on the form

mfeingold
I'm not sure how I would have broken anything... All I changed was the code seen in `FirstForm`. I feel like this shouldn't break anything...
Daniel Rasmussen
A: 

If you click multiple times, then the reference in FirstForm may no longer point to whatever you are closing.

try

 private void button1_Click(object sender, EventArgs e)
 {
      var second = new SecondForm();
      second.Show();
 }
BioBuckyBall
No, don't dispose a form right after showing it.
Hans Passant
Even if I only create a single instance of the second form, it doesn't dispose properly.
Daniel Rasmussen
@Hans - oops :) I blame...myself. The original point stands though. Code edited.
BioBuckyBall
A: 

The problem was a PowerPacks.RectangleShape object I had placed on my second form and forgot about (because it wouldn't render.) I deleted the object, and the form disposed just fine.

Testing this further, I found that any control which requires a PowerPacks.ShapeContainer (LineShape, OvalShape, and RectangleShape,) cause this problem, but other PowerPacks objects don't.

I'm not sure why this happens, so if anyone figures out a workaround, it'd be appreciated, but for now I'll avoid PowerPacks shapes.

Daniel Rasmussen