(论坛答疑点滴)怎么给Table动态添加控件并且得到控件的值?
[作者]:菩提树下的杨过 [来源]:互联网 [收录时间]:2007-8-18 14:59:23
此例子达到的效果是:
每按一次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+"
");
}

}

其实动态添加的控件不复杂,只需要注意一点:动态添加的控件在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),因为页面第一次加载不可能已经按下按钮了。