ITPub博客

首页 > IT职业 > IT生活 > 点击一次铵钮产生一个新文本框,分别输入值,然后获取

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

IT生活 作者:limiao 时间:2021-09-09 10:11:53 0 删除 编辑


 

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

5acf071e0001405b00110016.jpgView 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" />

 

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

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

 

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

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

 

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

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

 

Click事件:

5acf071e0001405b00110016.jpgView Code  protected void ButtonAdd_Click(object sender, EventArgs e)
    {
        TotalControls = TotalControls + 1;
        DymanicallyGenerateTextBoxControl(TotalControls);
    }

 

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

5acf071e0001405b00110016.jpgView 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/>");
        }
    }

 

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/4549/viewspace-2817947/ ,如需转载,请注明出处,否则将追究法律责任。

上一篇: Odds Ratio
请登录后发表评论 登录
全部评论

注册时间:2019-07-10

  • 博文量
    190
  • 访问量
    1372