简体   繁体   中英

Add asp:textbox dynamically in ASP.NET

I have an aspx page made with ASP.NET Web Forms. What i need to create is two asp:textbox fields. I want to be able to dynamically add two new fields below that with the press of a button.

So basically i want to be able to add an infinite amount of "new" textfields. But i'm not sure how to do this in ASP.NET.

Is there perhaps a way to create an arrat of those textfields? So that when a form is posted i can easily iterate over them?

How can i do this?

In your aspx file:

 <asp:TextBox runat="server" ID="textbox1"/>
 <asp:TextBox runat="server" ID="textbox2"/>

 <asp:Button runat="server" ID="btnAdd" OnClick="btnAdd_Click" />
 <asp:PlaceHolder runat="server" ID="ph" />

In your aspx.cs file:

 protected void btnAdd_Click(object sender, EventArgs e)
 {
      TextBox tb1 = new TextBox();
      TextBox tb2 = new TextBox();
      ph.Controls.Add(tb1);
      ph.Controls.Add(tb2);
 }

You can add this fields and make them hidden(invisible). And you can show fields on button click (with javascript). Dynamically adding serverside controls is problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM