Dynamically Create Textboxes in Asp.Net C# and Save Data in Database

← PrevNext →

Last updated: 14th November 2024

This example also shows how to call a WebMethod in Asp.Net using jQuery Ajax.

The HtmlGenericControl Class in Asp.Net, provides all the necessary methods and properties to create dynamic elements at the server side, through a code behind procedure. Here in this article I am going to show you how to create multiple textboxes dynamically in Asp.Net using the HtmlGenericControl class in C# and VB.NET and finally save the data in an SQL Server database table.

Scenario

I have a Students table in my SQL Server database that contains several columns. My goal is to populate this table with data entered through dynamically generated form fields on a web page.

To achieve this, I’ve added a button control on the page. When the user clicks the button, a server-side procedure retrieves the column names from the "Students" table and uses them to dynamically create corresponding textboxes for data entry.

Since these input elements are generated at runtime, I’ll leverage jQuery to extract the entered values. The data will then be sent via Ajax to a Web Method, which handles inserting the records into the database.

What it does?

Dynamic UI Creation: Uses HtmlGenericControl and server-side logic to dynamically generate input fields based on database column names. This keeps the form in sync with the schema.

Client-Side Extraction: Assigning a common class (.fld) to the textboxes allows jQuery to easily extract their values.

Asynchronous Save: Utilizes jQuery Ajax to call a [WebMethod], saving the form data without a full postback. That’s efficient and modern.

The Students Table (SQL Server)

The table has four columns.

CREATE TABLE Students (
    ID int IDENTITY(1,1) PRIMARY KEY,
    Name varchar(255) NOT NULL,
    Address varchar(255),
    Age int
);
The Markup

In the markup section, there is a button control that triggers a code-behind method on click, responsible for dynamically generating the textboxes. These textboxes are hosted within a <div> element, which serves as a container for the input fields. Additionally, there is a secondary button, initially hidden, that is used to submit the entered data once the form is completed.

<div class="main">
    <div>
        <asp:Button ID="bt" runat="server" Text="Create a Form" OnClick="createForm" />
    </div>

    <h2>Students Info</h2>

    <div id="columns" runat="server" 
        style="height:auto;
        width:300px;
        overflow:auto;">

    </div>
    <input type="button" id="submit" value="Submit" runat="server" style="display:none;" />
</div>

Let us now write the code to create the textboxes through a code behind procedure.

Dynamically Create Multiple Textboxes

C# Code

using System;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Data.SqlClient;
using System.Web.UI.HtmlControls;

public partial class SiteMaster : System.Web.UI.MasterPage
{
    SqlConnection myConn = default(SqlConnection);
    const string sConnString = "Data Source=DNA;Persist Security Info=False;" + 
        "Initial Catalog=DNA_Classified;User Id=sa;Password=demo;Connect Timeout=30;";

    protected void createForm(object sender, EventArgs e)
    {
        using (SqlConnection con = new SqlConnection(sConnString))
        {
            string sSQL = "SELECT Name FROM sys.columns " + 
                "WHERE object_id = OBJECT_ID('dbo.Students')";

            SqlCommand objComm = new SqlCommand(sSQL, con);
            con.Open();

            SqlDataReader reader = objComm.ExecuteReader();

            int iCnt = 0;       // JUST A COUNTER.

            while (reader.Read())
            {
                if (iCnt >= 1)
                {
                    HtmlGenericControl ul = new HtmlGenericControl("ul");
                    ul.Attributes.Add("style", "margin:2px 0;padding:0;");

                    HtmlGenericControl liCol = new HtmlGenericControl("li");
                    HtmlGenericControl spanCol = new HtmlGenericControl("span");

                    spanCol.InnerHtml = reader["Name"].ToString();
                    liCol.Attributes.Add("style", "width:30%;float:left;");
                    liCol.Controls.Add(spanCol);

                    // CREATE AN INSTANCE OF TEXTBOX.
                    // WITH EVERY COLUMN NAME, WE'LL CREATE AND ADD A TEXTBOX.
                    TextBox txt = new TextBox();
                    txt.ID = reader["Name"].ToString();

                    // ASSIGN A CLASS. WE'LL USE THE CLASS NAME TO EXTRACT DATA USING JQUERY.
                    txt.CssClass = "fld";

                    HtmlGenericControl liTxt = new HtmlGenericControl("li");
                    liTxt.Attributes.Add("style", "width:auto;");
                    liTxt.Controls.Add(txt);    // ADD THE NEWLY CREATED TEXTBOX TO A LIST.

                    ul.Controls.Add(liCol);
                    ul.Controls.Add(liTxt);

                    columns.Controls.Add(ul);
                }
                iCnt = iCnt + 1;
            }

            submit.Attributes.Add("style", "display:block;float:right;margin:10px;");
        }
    }
}

Run the application. The web page will display a button control. When clicked, it dynamically generates three empty textboxes along with a Submit button. All of these input elements are created at runtime through server-side logic.

imageCreate Multiple Textboxes Dynamically using Asp.Net C#

VB.NET Code

Option Explicit On
Imports System.Data.SqlClient

Partial Class Site
    Inherits System.Web.UI.MasterPage

    Dim myConn As SqlConnection

    Const sConnString As String = "Data Source=DNA;Persist Security Info=False;" & _
        "Initial Catalog=DNA_Classified;User Id=sa;Password=demo;Connect Timeout=30;"

    Protected Sub createForm(ByVal sender As Object, ByVal e As EventArgs)

        Using con As SqlConnection = New SqlConnection(sConnString)
            Dim sSQL As String = "SELECT Name FROM sys.columns " & _
                "WHERE object_id = OBJECT_ID('dbo.Students')"

            Dim objComm As New SqlCommand(sSQL, con)
            con.Open()

            Dim reader As SqlDataReader = objComm.ExecuteReader()

            Dim iCnt As Integer = 0

            While reader.Read
                If Val(iCnt) >= 1 Then
                    Dim ul As New HtmlGenericControl("ul")
                    ul.Attributes.Add("style", "margin:2px 0;padding:0;")

                    Dim liCol As New HtmlGenericControl("li")
                    Dim spanCol As New HtmlGenericControl("span")

                    spanCol.InnerHtml = reader.Item("Name")
                    liCol.Attributes.Add("style", "width:30%;float:left;")
                    liCol.Controls.Add(spanCol)

                    ' CREATE AN INSTANCE OF TEXTBOX.
                    ' WITH EVERY COLUMN NAME, WE'LL CREATE AND ADD A TEXTBOX.
                    Dim txt As New TextBox()
                    txt.ID = reader.Item("Name")

                    ' ASSIGN A CLASS. WE'LL USE THE CLASS NAME TO EXTRACT DATA USING JQUERY.
                    txt.CssClass = "fld"

                    Dim liTxt As New HtmlGenericControl("li")
                    liTxt.Attributes.Add("style", "width:auto;")
                    liTxt.Controls.Add(txt)    ' ADD THE NEWLY CREATED TEXTBOX TO A LIST.

                    ul.Controls.Add(liCol)
                    ul.Controls.Add(liTxt)

                    columns.Controls.Add(ul)
                End If

                iCnt = iCnt + 1
            End While

            submit.Attributes.Add("style", "display:block;float:right;margin:10px;")
        End Using
    End Sub
End Class

👍 The input controls are generated dynamically using a server-side (code-behind) procedure. Now, let’s implement a Web Method to save the entered data into the database.

Save data in Database

The Web Method will take a string value as parameter. The values are the contents from the textboxes.

Web Method (C#)
[System.Web.Services.WebMethod()]
public static string addStudents(string val)
{
    string functionReturnValue = null;
    try
    {
        using (SqlConnection con = new SqlConnection(sConnString))
        {
            string sQuery = null;
            sQuery = "INSERT INTO dbo.Students (Name, Address, Age)" + 
                "VALUES (" + HttpUtility.UrlDecode(val) + ")";

            using (SqlCommand cmd = new SqlCommand(sQuery))
            {
                cmd.Connection = con;
                con.Open();

                cmd.ExecuteNonQuery();
                con.Close();

                functionReturnValue = "Success";
            }
        }
    }
    catch (Exception ex)
    {         functionReturnValue = "There was an error";     }
    finally
    {     }

    return functionReturnValue;
}
Web Method (Vb)
<System.Web.Services.WebMethod()> _
Public Shared Function addStudents(ByVal val As String) As String
    Try
        Using con As SqlConnection = New SqlConnection(sConnString)
            Dim sQuery As String
            sQuery = "INSERT INTO dbo.Students (Name, Address, Age)" & _
                "VALUES (" & HttpUtility.UrlDecode(val) & ")"

            Using cmd As SqlCommand = New SqlCommand(sQuery)
                With cmd
                    .Connection = con
                    con.Open()

                    cmd.ExecuteNonQuery()
                    con.Close()

                    addStudents = "Success"
                End With
            End Using
        End Using
    Catch ex As Exception
        addStudents = "There was an error"
    Finally
        '
    End Try
    
    Return addStudents
End Function

Finally, we’ll write the script to make an Ajax call to our Web Method.

The jQuery Ajax
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>

<script>
    $(document).ready(function () {
        BindControls();
    });

    // CALL A WEB METHOD TO SAVE DATA USING AJAX.
    function BindControls() {
        $('#submit').click(function () {
            saveTextValue();
        });

        var values = new Array();

        function saveTextValue() {

            // While creating the textboxes through a code behind procedure, 
            // I have assigned a class named "fld" to each textbox.
            // Using the "fld" class name, we can easily extract values from the input boxes.
            $('.fld').each(function () {
                if (this.value != '') {
                    values.push("'" + this.value + "'");
                }
            });

            if (values != '') {
                // ONCE WE HAVE ALL THE VALUES, MAKE THE CALL TO OUR WEB METHOD.
                $.ajax({
                    type: 'POST',
                    url: 'https://localhost:53094/csharp/default.aspx/addStudents',
                    data: "{'val':'" + escape(values) + "'}",
                    dataType: 'json',
                    headers: { "Content-Type": "application/json" },
                    success: function (response) {
                        alert(response.d);      // DONE.
                        values = '';
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        alert(errorThrown);
                    }
                });
            }
            else { alert("Fields cannot be empty.") }
        }
    }
</script>

← PreviousNext →