How to dynamically create textbox in c# on button click according to user input value?

How to dynamically create a textbox in c# on button click, according to user input value?

Asked by:- VivekVishwas
: 9334 At:- 11/6/2017 3:56:54 PM
c# sql

1 Answers
profileImage Answered by:- manish

You can create and get the value of dynamically created text box in web forms using the below code

Web-forms .aspx HTML code

<asp:Panel ID="pnlTextBoxes" runat="server">
<hr />
<asp:Button ID="btnAdd" runat="server" Text="Add New" OnClick="AddTextBox" />
<asp:Button ID="btnGet" runat="server" Text="Get Values" OnClick="GetTextBoxValues" />

C# Code behind

//retain the dynamic TextBoxes across PostBacks
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 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 />";

//Get Value of textbox
protected void GetTextBoxValues(object sender, EventArgs e)
    string message = "";
    foreach (TextBox textBox in pnlTextBoxes.Controls.OfType<TextBox>())
        message += textBox.ID + ": " + textBox.Text + "\\n";
    ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "alert('" + message + "');", true);

The above code Adds textbox dynamically, and get it's value 

Few more links which may help

1. (To add Textbox, Dropdown list, radio button and checkbox)






Hope this helps, thanks

At:- 11/7/2017 3:47:24 AM
yeah, suppose , there is 6 text box generated dynamically, I entered some value in each text , and i want to save that value in database. how do i perform that task. Please answer me urgently 0
By : VivekVishwas - at :- 11/7/2017 8:12:52 AM
@vivek, please check answer carefully, there is a code to get Dynamically added values , you can modify it, and loop through all textbox and save it in Database Hope this solved your query, if not, please attach images of error you are facing, you can 'Edit question' & add more details when needed, thanks 0
By : vikas_jk - at :- 11/7/2017 10:24:17 AM

Login/Register to answer
Register directly by posting answer/details

Full Name *

Email *

By posting your answer you agree on privacy policy & terms of use