0

我有几个不同的自定义控件,它们从不同的 Web 控件扩展而来:

  • RulesPanel: Panel包含一个Table和一些其他控件。使用可变数量的对象Table动态填充。RuleRow其他控件包括增加行数的方法。
  • RuleRow: TableRow包含三个RuleCell对象
  • RuleCell: TableCell包含一个Panel动态填充可变数量的RuleData控件。它还包含面板之外的一些其他控件,用于增加面板内部的控件数量。
  • RuleData: 扩展自Table包含固定数量的单元格和控件的控件。

对于RulesPanel,我想将它具有的行数保存到控制状态。对于RulesCell,我想保存其面板内的控件数量。我对两者都做了类似的事情(使用表格而不是面板RulesPanel):

protected override void OnInit(EventArgs e)
{
    Page.RegisterRequiresControlState(this);
    base.OnInit(e);
}
protected override object SaveControlState()
{
    return new Pair(base.SaveControlState(), pnlChildren.Controls.Count);
}
protected override void LoadControlState(object savedState)
{
    Pair controlState = savedState as Pair;
    base.LoadControlState(controlState.First);
    if ((Int32)controlState.Second > pnlChildren.Controls.Count)
    {
        AddChildren((Int32)controlState.Second - pnlChildren.Controls.Count);
    }
}

编辑: 这是事件处理程序和它为RuleCell类调用的 AddChildren 函数。有一组类似的RulesPanel方法,但它将RuleRow对象添加到其表而不是RuleData对象到面板。

protected void btnNeedMore_click(object sender, EventArgs e)
{
    Int32 numToAdd;
    if (Int32.TryParse(txtNeedMore.Text, out numToAdd))
    {
        AddChildren(numToAdd);
        txtNeedMore.Text = "";
    }
}
private void AddChildren(Int32 numberToAdd)
{
    Int32 totalNumber = pnlChildren.Controls.Count + numberToAdd;
    for (Int32 i = pnlChildren.Controls.Count; i < totalNumber; i++)
    {
        pnlChildren.Controls.Add(new RuleData(i));
    }
}

RuleCell对象行为正确。但是,当我RuleRow向 a 添加更多对象时RulesPanel(通过单击按钮的回发事件),下一次回发将导致 VS2012 调试器无法访问的“集合已修改”异常,就像这里一样。

Collection was modified; enumeration operation may not execute.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.InvalidOperationException: Collection was modified; enumeration operation may not execute.

Source Error: 

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace: 


[InvalidOperationException: Collection was modified; enumeration operation may not execute.]
   System.Collections.HashtableEnumerator.MoveNext() +10715184
   System.Web.UI.Page.LoadAllState() +292
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1849

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18055

为什么?

4

0 回答 0