(論壇答疑點滴)怎麼給Table動態添加控件並且得到控件的值?

- 中國WEB開發者網絡 (http://www.webasp.net)
-- 技術教程 (http://www.webasp.net/article/)
--- (論壇答疑點滴)怎麼給Table動態添加控件並且得到控件的值? (http://www.webasp.net/article/18/17832.htm)
-- 作者:未知
-- 發佈日期: 2005-04-22
此例子達到的效果是:
每按一次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),因為頁面第一次加載不可能已經按下按鈕了。


webasp.net