Dynamically add a new text box when clicking a button

asp.net, c#, controls, dynamic

Solution

Reason: When you click button again than it do postback to serverside and it removes previously added dynamically textbox

Solution: To add it again you need to do like this

 TextBox tb;
static int i = 0;
protected void addnewtext_Click(object sender, EventArgs e)
{
        i++;
    for(j=0;j<=i;j++)
    {
    tb = new TextBox();
    tb.ID = j.ToString();

    PlaceHolder1.Controls.Add(tb);
    }

}

that means you need to create the added textbox again...because you are adding control dynamically to the page...

Article like this might help you : Retaining State for Dynamically Created Controls in ASP.NET applications

Problem

I'm using this code ``` <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder> <asp:Button ID="addnewtext" runat="server" Text="Add" onclick="addnewtext_Click" width="76px" /> ``` and aspx.cs page code: ``` TextBox tb; static int i = 0; protected void addnewtext_Click(object sender, EventArgs e) { tb = new TextBox(); tb.ID = i.ToString(); PlaceHolder1.Controls.Add(tb); i++; } ``` On every click on the button I want to add another text box.

Original source