How to dynamically create a textbox in asp.net c# on button click, according to user input value?
You can create and get the value of dynamically created text box in asp.net web forms using the below code
Web-forms .aspx HTML code
<asp:Panel ID="pnlTextBoxes" runat="server">
</asp:Panel>
<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);
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;
pnlTextBoxes.Controls.Add(txt);
Literal lt = new Literal();
lt.Text = "<br />";
pnlTextBoxes.Controls.Add(lt);
}
//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.http://sunilgurjaraspdotnet.blogspot.in/2012/07/add-dynamic-controlstext-box_3.html (To add Textbox, Dropdown list, radio button and checkbox)
2. https://www.codeproject.com/Questions/453289/How-to-dynamically-create-textboxes-in-asp-net-and
3. http://crazygeeksblog.com/2014/02/c-net-dynamically-create-textbox-in-asp-net/
4. http://www.dotnetspark.com/kb/1368-create-and-retrieve-value-from-dynamic-controls.aspx
5. http://www.itprotoday.com/web-development/manage-dynamically-created-controls
6. http://www.nullskull.com/q/10299810/how-can-i-add-labels-and-textbox-to-aspx-page-dynamically.aspx
Hope this helps, thanks
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly