さまざまな Web コントロールから拡張されたいくつかの異なるカスタム コントロールがあります。
RulesPanel: Panel
およびその他のいくつかのコントロールが含まれていTable
ます。Table
には可変数のオブジェクトが動的に読み込まれますRuleRow
。他のコントロールには、行数を増やす方法が含まれています。RuleRow: TableRow
3 つの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 デバッガーの範囲外で「コレクションが変更されました」という例外が発生します。
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
なんで?