无法嵌套使用控件状态的动态服务器控件

时间:2013-11-13 22:02:15

标签: c# asp.net

我有一些不同的自定义控件,可以从不同的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添加更多RulesPanel个对象时(通过单击按钮的回发事件),下一个回发将导致VS2012调试器无法访问的“收集已修改”异常,就像here

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

为什么?

0 个答案:

没有答案
相关问题