点击一次铵钮产生一个新文本框,分别输入值,然后获取

参考前一篇,http://www.cnblogs.com/insus/archive/2012/09/23/2698613.html 没有达到用户的要求,用户要求是每点击一次添加铵钮,产生一个新的文本框TextBox,在文本框输入一些值之后,点击获取文本框值的铵钮,能取得刚才在文本框的值。首先看看修改之后的效果:

 

 

xxx.aspx:在网页中,拉一个动态添加文本框装载的容器PlaceHolder,和两个铵钮,一个是添加,另一个是获取值。

ExpandedBlockStart.gif View Code
  < asp:PlaceHolder  ID ="PlaceHolder1"  runat ="server" ></ asp:PlaceHolder >
             < br  />
             < asp:Button  ID ="ButtonAdd"  runat ="server"  Text ="Add TextBox"   OnClick ="ButtonAdd_Click"   />
             < asp:Button  ID ="ButtonGetValue"  runat ="server"  Text ="GetTextValue"  OnClick ="ButtonGetValue_Click"   />

 

为了记录添加的次数,我们需要写一个属性,记得点击次数。

ExpandedBlockStart.gif TotalControls
  protected  int TotalControls
    {
         get 
        {
             return ViewState[ " TotControls "] ==  null ?  0 : ( int)(ViewState[ " TotControls "]); 
        }
         set 
        { 
            ViewState[ " TotControls "] = value; 
        }
    }

 

写一个方法,动态产生文本框,方法有一个参数,就是传入将要产生的次数。

ExpandedBlockStart.gif View Code
  private  void DymanicallyGenerateTextBoxControl( int totalControls)
    {
        TextBox tb =  new TextBox();
        tb.ID =  " TextBox " + totalControls;
         this.PlaceHolder1.Controls.Add(tb);
    }

 

网页一加载时,Page_Load事件中,判断计数器为多少,循环产生文本框。

ExpandedBlockStart.gif View Code
  protected  void Page_Load( object sender, EventArgs e)
    {
         for ( int i =  0; i < TotalControls; i++)
        {
            DymanicallyGenerateTextBoxControl(i +  1);
        }       
    }

 

Click事件:

ExpandedBlockStart.gif View Code
  protected  void ButtonAdd_Click( object sender, EventArgs e)
    {
        TotalControls = TotalControls +  1;
        DymanicallyGenerateTextBoxControl(TotalControls);
    }

 

最后是获取文本框值的铵钮Click事件:

ExpandedBlockStart.gif View Code
  protected  void ButtonGetValue_Click( object sender, EventArgs e)
    {
         foreach (Control ctl  in  this.PlaceHolder1.Controls)
        {
             if (ctl  is TextBox)
                Response.Write(((TextBox)ctl).Text.Trim () +  " <br/> ");
        }
    }

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值