In this article I will explain with an example, how to create Dynamic TextBox controls in ASP.Net using C# and VB.Net.
HTML Markup
The HTML Markup consists of:
Panel – For adding Dynamic TextBoxes.
Button – For creating Dynamic TextBoxes.
The Button has been assigned with an OnClick event handler.
<asp:Panel ID="pnlTextBoxes" runat="server"></asp:Panel>
<hr  />
<asp:Button ID="btnAdd" runat="server" Text="Add New" OnClick="AddTextBox" />
Dynamically creating and adding TextBoxes on Button Click
When the Add Button is clicked, first the count of all the TextBoxes present in the Panel control is determined and then the Count is incremented to generate an Index.
The Index will be used for generating unique ID for the TextBox control.
Note: It is very important to give a common prefix (example txtDynamic) for all TextBoxes as it will be used to find and recreate all Dynamic TextBoxes on PostBack.
Then, CreateTextBox method is called which accepts generated index as parameter.
The CreateTextBox method accepts unique ID as a parameter.
Inside this method, an object of TextBox class is created and unique ID is assigned to the ID property of the TextBox.
Finally, the TextBox is appends to the Panel control using Add method.
protected void AddTextBox(object sender, EventArgs e)
    int index = pnlTextBoxes.Controls.OfType<TextBox>().ToList().Count + 1;
    this.CreateTextBox("txtDynamic" + index);
private void CreateTextBox(string id)
    TextBox txt = new TextBox();
    txt.ID = id;
    Literal lt = new Literal();
    lt.Text = "<br />";
Protected Sub AddTextBox(sender As Object, e As EventArgs)
    Dim index As Integer = pnlTextBoxes.Controls.OfType(Of TextBox)().ToList().Count + 1
    Me.CreateTextBox("txtDynamic" & index)
End Sub
Private Sub CreateTextBox(id As String)
    Dim txt As New TextBox()
    txt.ID = id
    Dim lt As New Literal()
    lt.Text = "<br />"
End Sub
Retaining the Dynamic TextBoxes on PostBack
In order to retain the Dynamic TextBoxes across PostBacks, the PreInit event handler of the Page is used to recreate the Dynamic TextBoxes.
First, the generic List is created and the keys containing the Dynamic TextBoxes are fetched using Lambda expression.
Then, using a FOR EACH loop, one by one each Dynamic TextBox is recreated using CreateTextBox method..
protected void Page_PreInit(object sender, EventArgs e)
    List<string> keys = Request.Form.AllKeys.Where(key => key.Contains("txtDynamic")).ToList();
    int i = 1;
    foreach (string key in keys)
        this.CreateTextBox("txtDynamic" + i);
Protected Sub Page_PreInit(sender As Object, e As EventArgsHandles Me.PreInit
    Dim keys As List(Of String) = Request.Form.AllKeys.Where(Function(key) key.Contains("txtDynamic")).ToList()
    Dim i As Integer = 1
    For Each key As String In keys
        Me.CreateTextBox("txtDynamic" & i)
        i += 1
End Sub
Creating Dynamic TextBox Controls in ASP.Net