asp.net动态添加控件和获取控件的值
有很多时候我们需要动态的添加控件,以适应客户的需求,下面的小例子演示了如何动态的添加控件和获取控件的值。
1、添加控件
 protected void Page_Load(object sender, EventArgs e)
    
{
        
int counts = 4;//假设添加四个控件
        for (int i = 1; i <= counts; i++)
        
{
            TableRow row 
= new TableRow();
            TableCell cellHead 
= new TableCell();
            TableCell cellContent 
= new TableCell();
            Label LabelAuditing 
= new Label();
            TextBox TextAuditing 
= new TextBox();
            LabelAuditing.ID 
= "LabelAuditing" + i.ToString();
            LabelAuditing.Text 
= "LabelAuditing" + i.ToString();
            TextAuditing.ID 
= "TextAuditing" + i.ToString();
            TextAuditing.Height 
= 18;
            cellHead.Controls.Add(LabelAuditing);
            cellContent.Controls.Add(TextAuditing);             
            cellHead.BackColor 
= System.Drawing.Color.FromName("#EFEFEF");
            cellHead.BorderWidth 
= 1;
            cellHead.BorderColor 
= System.Drawing.Color.FromName("#CCCCCC");
            cellHead.HorizontalAlign 
= HorizontalAlign.Left;
            cellHead.Width 
= 60;
            cellContent.BorderColor 
= System.Drawing.Color.FromName("#CCCCCC");
            cellContent.BackColor 
= System.Drawing.Color.FromName("#EFEFEF");
            cellContent.BorderWidth 
=1;
            cellContent.HorizontalAlign 
= HorizontalAlign.Left;
            cellContent.Width 
= 100;
            row.Cells.Add(cellHead);
            row.Cells.Add(cellContent);
            row.Height 
= 22;
            
this.Table1.BorderColor = System.Drawing.Color.FromName("#CCCCCC");            
            
this.Table1.Width = 400;
            
this.Table1.Rows.Add(row);
        }

    }

2、获取控件的值
protected void Button1_Click(object sender, EventArgs e)
    
{
        
string str = string.Empty;
        
for (int i = 1; i <= 4; i++)
        
{
            str 
+= ((TextBox)this.FindControl("TextAuditing" + i.ToString())).Text+"<br>";//获取控件的值
        }

        
this.LabelMsg.Text = str;
    }

3、前台的代码
<form id="form1" runat="server">
    
<div>
        
<br />
        
<table border="0" cellpadding="0" cellspacing="0" style="width: 400px; height: 134px">
            
<tr>
                
<td class="tabnotop"  style="height: 18px">
        
<asp:Table ID="Table1" runat="server" CellPadding="0" CellSpacing="0" Height="56px"
            Width
="142px" BorderWidth="1px">
        
</asp:Table>
                
</td>
            
</tr>
            
<tr>
                
<td style="height: 29px; text-align: center">
                    
<asp:Button ID="Button1" runat="server" CssClass="btnew" OnClick="Button1_Click"
                        Text
="确定" /></td>
            
</tr>
        
</table>
        
<asp:Label ID="LabelMsg" runat="server"></asp:Label><br />
        
&nbsp;<br />
    
    
</div>
    
</form>

4、运行结果
 posted on 2012-07-11 17:36  纳米程序员  阅读(9138)  评论(0编辑  收藏  举报