0

“集合已修改;枚举操作可能无法执行。” 似乎是foreach循环的常见错误,但我无法弄清楚。我有两类表格。一个在启动时开始,一个按钮创建第二种形式的新实例,并显示它们。当我关闭辅助表单时,我得到一个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.
    }
}
4

3 回答 3

0

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, I'd appreciate that. But for now I'll avoid PowerPacks shapes.

于 2010-05-19T13:09:51.230 回答
0

会不会是递归调用Dispose?可以看看异常发生时的调用栈吗?

如果是这种情况,损坏的集合将是表单上的控件集合

于 2010-05-18T21:37:26.777 回答
0

如果您单击多次,则 FirstForm 中的引用可能不再指向您正在关闭的任何内容。

尝试

 private void button1_Click(object sender, EventArgs e)
 {
      var second = new SecondForm();
      second.Show();
 }
于 2010-05-18T22:28:00.780 回答