【发布时间】:2015-06-25 13:46:19
【问题描述】:
我有一个自定义控件 (customContainer),它可以容纳多个 ConditionControl 类型的自定义控件。当我单击 customContainer 控件中的按钮时,我想将另一个 customControl 添加到我的容器中。
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
CustomControlsPanel.Controls.Add(new LiteralControl("<br />"));
ConditionControl myCc = (ConditionControl)LoadControl(@"~/ConditionControl.ascx");
CustomControlsPanel.Controls.Add(myCc);
}
这只能工作一次。所以我单击它一次,它添加了一个条件控件,但它不再工作了。我该如何解决这个问题?
编辑:我尝试将面板的控件集合保存到会话变量中,然后使用它来恢复控件,如下所示:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Session["controls"] = ConditionControlsPanel.Controls;
}
else
{
ControlCollection temp = (ControlCollection)Session["controls"];
ConditionControlsPanel.Controls.Clear();
foreach (Control ctrl in temp)
{
ConditionControlsPanel.Controls.Add(ctrl);
}
}
}
当我尝试执行 foreach 时,当我尝试添加一个新控件说 Collection was modified; enumeration operation may not execute. 时出现错误
【问题讨论】: