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


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

 

 

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

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"   />

 

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

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

 

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

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

 

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

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

 

Click事件:

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

 

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

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/> ");
        }
    }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM