我正在以編程方式將面板添加到另一個面板(我稱這些面板塊爲更好理解)。每個塊都包含一個標題,一個用於向塊添加文本框的按鈕和一個起始文本框。動態添加文本框以動態添加面板
這是我使用添加文本框的事件:
/// <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>()
});
}
然而,我每次添加一個文本框,我剛剛創建被刪除
編輯這是怎樣的一個我最終解決它(感謝唐):
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 });
那與動態控制工作時是真正的痛苦。 – niksofteng
嗨,謝謝你的回答。什麼是正確/最好的方式來存儲? –
我會將它存儲在List或Array中並將其存儲在ViewState中。通過這種方式,列表/數組在回發期間可用 – Don