(論壇答疑點滴)怎麼給Table動態添加控制項並且得到控制項的值?
來源:互聯網
上載者:User
動態|控制項 此例子達到的效果是:
每按一次Button1,在表格Table1中添加一行(行中有2列,一列是文字框,一列是下拉框),並且當按鈕第一次按下時再添加一個按鈕,點擊這個動態添加的按鈕,輸出表格中所有的控制項的值。
前台:
<form id="Form1" method="post" runat="server">
<asp:Table id="Table1" runat="server"></asp:Table>
<asp:PlaceHolder id="PlaceHolder1" runat="server"></asp:PlaceHolder><BR><BR>
<asp:Button id="Button1" runat="server" Text="添加一行"></asp:Button>
</form>
放置一個Table用來動態添加控制項,放置一個PlaceHolder用來動態添加按鈕,按下這個按鈕得到表中控制項的值,按下Button1按鈕一次就添加一行。
後台:
Button1按鈕的事件:
private void Button1_Click(object sender, System.EventArgs e)
{
AddTextBoxs();
if(ViewState["Count"]==null)AddButton();
ViewState["Count"]=Convert.ToInt16(ViewState["Count"])+1;
}
兩個方法:一個用來動態添加表格中的行,一個用來動態添加按鈕(按鈕不是按下Button1添加一次的,所以加上if(ViewState["Count"]==null)表示只有第一次載入按下按鈕的時候才添加)
private 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);
}
private void AddButton()
{
Button b=new Button();
b.ID="btn";
b.Text="按鈕";
b.Click += new System.EventHandler(btn_Click);
PlaceHolder1.Controls.Add(b);
}
最後是那個動態添加的按鈕的事件:
private void btn_Click(object sender, System.EventArgs e)
{
for(int i=0;i<Table1.Rows.Count;i++)
{
Response.Write(((TextBox)Table1.Rows[i].FindControl("tb"+i)).Text+((DropDownList)Table1.Rows[i].FindControl("dpl"+i)).SelectedValue+"<br>");
}
}
其實動態添加的控制項不複雜,只需要注意一點:動態添加的控制項在PostBack的時候也需要再次添加,那麼怎麼知道是不是按下了按鈕,或者說怎麼知道已經按了幾次按鈕?就用一個標示位存放在ViewState中即可。
Page_Load事件:
private void Page_Load(object sender, System.EventArgs e)
{
if(ViewState["Count"]!=null)
{
for(int i=0;i<Convert.ToInt16(ViewState["Count"]);i++)
AddTextBoxs();
AddButton();
}
} 注意不要添加if(!IsPostBack){},相反你倒可以添加if(IsPostBack),因為頁面第一次載入不可能已經按下按鈕了。