Create Textbox Dynamically using JavaScript and Read Value In C#

This article will show you how to create textbox control from JavaScript and then read their values in C#.
Create an 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" "">
<html xmlns="">
<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.innerHTML = '<input type="text"  name="TextBox'+num+'" value="TextBox'+num+'" >';    


  <title>Untitled Page</title>
  <form id="form1" runat="server">
      <asp:GridView ID="GridView1" runat="server">
      <div id="myDiv">
      <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" />


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();
            strValue = "";

 //Uncomment this line and test.
    //foreach (string x in Request.Form)

    //   string strValue = Request.Form[x].ToString();
     //  alForm.Add(strValue);

  GridView1.DataSource = alForm;

Next Post Previous Post
No Comment
Add Comment
comment url