因為項目需要,如何在Asp.Net頁面添加控制項。
其實部落格員都給出了答案,本文只是做了一些測試和總結
Asp.Net頁面添加控制項問題的關鍵就是原本在頁面載入的時候所有的控制項初始化操作都應該完成,動態載入將載入的過程延遲到了事件被觸發之後,因此在頁面回傳後, 因為會有一次新的頁面載入過程,顯然這時候動態載入的控制項是不存在的,但是使用者預期的答案是顯示已經載入的資訊。這時候如果可能我們最好在載入的過程中進 行控制項的重新載入和資料繫結。
按照一般人的思維想法,都會使用
public void AddTextBoxs()
{
TableRow tr = new TableRow();
TableCell tc1 = new TableCell();
TextBox t = new TextBox();
t.ID = "tb" + Table1.Rows.Count;
tc1.Controls.Add(t);
TableCell tc2 = new TableCell();
DropDownList dpl = new DropDownList();
dpl.ID = "dpl" + Table1.Rows.Count;
for (int i = 0; i < 10; i++) dpl.Items.Add(i.ToString());
tc2.Controls.Add(dpl);
tr.Cells.Add(tc1);
tr.Cells.Add(tc2);
Table1.Rows.Add(tr);
}
然後在一個button裡添加click事件
protected void Button1_Click(object sender, EventArgs e)
{
AddTextBoxs();
}
程式測試,頁面是可以產生相關的控制項。
問題出在,如果你再按其他按鈕會發現你添加的動態控制項消失啦,更別提如何取值拉?
根據尋找答案,原因是每次按鈕後,頁面重新post一次,必須重新添加相關的控制項 所以在formload event中添加
protected void Page_Load(object sender, EventArgs e)
{
if (ViewState["Count"] != null)
{
for (int i = 0; i < Convert.ToInt16(ViewState["Count"]); i++)
AddTextBoxs();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
AddTextBoxs();
if (ViewState["Count"] == null) AddButton();
ViewState["Count"] = Convert.ToInt16(ViewState["Count"]) + 1;
}