This article will show you how to create textbox control from JavaScript and then read their values in C#.
Create an asp.net
application with 2 Button and a Grandview’s shown below.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DynamicTextboxJavascript.aspx.cs"
Inherits="DynamicTextboxJavascript" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<script type="text/javascript">
function addElement() {
var ni = document.getElementById('myDiv');
var numi = document.getElementById('theValue');
var num = (document.getElementById('theValue').value -1)+2;
numi.value = num;
var newdiv = document.createElement('div');
var divIdName = 'my'+num+'Div';
newdiv.setAttribute('id',divIdName);
newdiv.innerHTML = '<input type="text" name="TextBox'+num+'" value="TextBox'+num+'" >';
ni.appendChild(newdiv);
}
</script>
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
<div id="myDiv">
</div>
<input type="button" id="btnOfficial" value="Add Another TextBox" onclick="addElement();" />
<input type="hidden" value="1" id="theValue" runat="server" />
<asp:Button ID="btnSave" runat="server" OnClick="btnSave_Click" Text="Read" />
</form>
</body>
</html>
STEP2
Add the following code behind.
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class DynamicTextboxJavascript : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSave_Click(object sender, EventArgs e)
{
ArrayList alForm = new ArrayList();
//Because my textbox id is started
// with 2 like(TextBox2,TextBox3.....
for (int i = 2; i< Request.Form.Count - 2;i++)
{
string strId = "TextBox" + i.ToString();
string strValue = Request.Form[strId].ToString();
alForm.Add(strValue);
strValue = "";
}
//Uncomment this line and test.
//foreach (string x in Request.Form)
//{
// string strValue = Request.Form[x].ToString();
// alForm.Add(strValue);
//}
GridView1.DataSource = alForm;
GridView1.DataBind();
}
}