【发布时间】:2015-10-16 14:31:32
【问题描述】:
我正在以编程方式将面板(我称此面板为块以便更好地理解)添加到另一个面板。这些块中的每一个都包含一个标题、一个向块中添加文本框的按钮和一个注视文本框。
这是我用来添加文本框的事件:
/// <summary>
/// Adds a text box to the button's parent
/// </summary>
protected void AddLabel_Click(object sender, EventArgs e)
{
Button senderButton = (Button)sender;
string parentId = senderButton.ID.Replace("_button","");
Panel parent = (Panel)FindControl(update_panel, parentId);
parent.Controls.Add(new TextBox
{
CssClass = "form-control canvas-label",
ID = parent.ID + "_label" + parent.Controls.OfType<TextBox>().Count<TextBox>()
});
}
但是,每次我添加一个文本框时,我刚刚创建的文本框都会被删除
编辑这就是我最终解决它的方式(感谢 Don):
1) 保留文本框列表
Dictionary<string, List<string>> BlocksLabels
{
get
{
if (ViewState["BlockLabels"] == null)
ViewState["BlockLabels"] = new Dictionary<string, List<string>>();
return ViewState["BlockLabels"] as Dictionary<string, List<string>>;
}
set { ViewState["BlockLabels"] = value; }
}
2) 在创建块的方法中(从 Page_Load 调用):
if (BlocksLabels.ContainsKey(block.ID))
{
foreach (string label in BlocksLabels[block.ID])
block.Controls.Add(new TextBox { ID = labelId });
}
else
{
// Add one empty canvas label by default
string labelId = block.ID + "_label0";
BlocksLabels[block.ID] = new List<string>();
BlocksLabels[block.ID].Add(labelId);
block.Controls.Add(new TextBox { ID = labelId });
}
3) 最后,在添加新文本框的情况下
Button senderButton = (Button)sender;
string parentId = senderButton.ID.Replace("_button", "");
Panel targetBlock = (Panel)FindControl(update_panel, parentId);
string labelId = targetBlock.ID + "_label" + BlocksLabels[targetBlock.ID].Count;
BlocksLabels[targetBlock.ID].Add(labelId);
targetBlock.Controls.Add(new TextBox { ID = labelId });
【问题讨论】: