In this article I will explain how to dynamically add rows to GridView on client side using JavaScript on Button click in ASP.Net.
The GridView Rows added using JavaScript on client side will be fetched on server side and inserted into the database.
 
 
Database
I have made use of the following table Customers with the schema as follows.
Dynamically Add Rows to GridView using JavaScript on Button Click in ASP.Net
 
Note: You can download the database table SQL by clicking the download link below.
          Download SQL file
 
 
HTML Markup
The following HTML Markup consists of an ASP.Net GridView, two TextBoxes and two Buttons. The Add button makes a call to a JavaScript function AddRow (discussed later).
<asp:GridView ID="gvCustomers" CssClass = "table" runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:TemplateField HeaderText="Name" ItemStyle-Width="150px" ItemStyle-CssClass="Name">
            <ItemTemplate>
                <%# Eval("Name") %>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Country" ItemStyle-Width="150px" ItemStyle-CssClass="Country">
            <ItemTemplate>
                <%# Eval("Country")%>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
<br />
<table border="0" cellpadding="0" cellspacing="0">
    <tr>
        <td style="width: 150px">
            Name:<br />
            <asp:TextBox ID="txtName" runat="server" Width="140" Text="" />
        </td>
        <td style="width: 150px">
            Country:<br />
            <asp:TextBox ID="txtCountry" runat="server" Width="140" Text="" />
        </td>
        <td style="width: 100px">
            <br />
            <asp:Button ID="btnAdd" runat="server" Text="Add" OnClientClick="return AddRow()" />
        </td>
    </tr>
</table>
<br />
<asp:Button Text="Submit" runat="server" OnClick="Submit" />
 
 
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
 
VB.Net
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
 
 
Populating the GridView from database
The GridView is populated with records from the Customers table inside the Page Load event. If there are no records then a dummy row is inserted into the DataTable before it is bound to the GridView.
Note: The dummy row is inserted because without any rows the GridView will not render on the page and thus it won’t be possible to access the GridView using JavaScript.
C#
protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        this.BindGrid();
    }
}
 
private void BindGrid()
{
    DataTable dt = new DataTable();
    string query = "SELECT Name, Country FROM Customers";
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand(query))
        {
            cmd.Connection = con;
            using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
            {
                sda.SelectCommand = cmd;
                sda.Fill(dt);
            }
        }
    }
 
    if (dt.Rows.Count == 0)
    {
        //If no records then add a dummy row.
        dt.Rows.Add();
    }
 
    gvCustomers.DataSource = dt;
    gvCustomers.DataBind();
}
 
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        Me.BindGrid()
    End If
End Sub
 
Private Sub BindGrid()
    Dim dt As New DataTable()
    Dim query As String = "SELECT Name, Country FROM Customers"
    Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using con As New SqlConnection(constr)
        Using cmd As New SqlCommand(query)
            cmd.Connection = con
            Using sda As New SqlDataAdapter(cmd)
               sda.SelectCommand = cmd
               sda.Fill(dt)
            End Using
        End Using
    End Using
 
    If dt.Rows.Count = 0 Then
        'If no records then add a dummy row.
        dt.Rows.Add()
    End If
 
    gvCustomers.DataSource = dt
    gvCustomers.DataBind()
End Sub
 
 
Adding Rows to GridView using JavaScript on Button Click
When the Add Button is clicked, the following JavaScript function is executed. Inside this function, first the GridView is referenced.
Note: The GridView is rendered as HTML Table in browser.
Using the GridView’s reference, the TBODY element is determined, which is contains all the rows of the HTML Table.
Then the first Row of the GridView is referenced in a JavaScript variable and if its Cells are empty then the GridView Row is considered as dummy row and it is removed from the GridView.
The values of both the TextBoxes are fetched and set in the respective Cells of the Row. Along with the values, a HiddenField is also added to each Cell of the Row.
Note: Only values of INPUT elements are posted to the server when a Form is submitted and hence we need to set values in HiddenFields so that we can retrieve the rows added to GridView on client side using JavaScript.
Finally the row is appended to the TBODY element of the HTML Table.
<script type="text/javascript">
function AddRow() {
    //Reference the GridView.
    var gridView = document.getElementById("<%=gvCustomers.ClientID %>");
 
    //Reference the TBODY tag.
    var tbody = gridView.getElementsByTagName("tbody")[0];
 
    //Reference the first row.
    var row = tbody.getElementsByTagName("tr")[1];
 
    //Check if row is dummy, if yes then remove.
    if (row.getElementsByTagName("td")[0].innerHTML.replace(/\s/g, '') == "") {
        tbody.removeChild(row);
    }
 
    //Clone the reference first row.
    row = row.cloneNode(true);
 
    //Add the Name value to first cell.
    var txtName = document.getElementById("<%=txtName.ClientID %>");
    SetValue(row, 0, "name", txtName);
 
    //Add the Country value to second cell.
    var txtCountry = document.getElementById("<%=txtCountry.ClientID %>");
    SetValue(row, 1, "country", txtCountry);
 
    //Add the row to the GridView.
    tbody.appendChild(row);
    return false;
};
 
function SetValue(row, index, name, textbox) {
    //Reference the Cell and set the value.
    row.cells[index].innerHTML = textbox.value;
           
    //Create and add a Hidden Field to send value to server.
    var input = document.createElement("input");
    input.type = "hidden";
    input.name = name;
    input.value = textbox.value;
    row.cells[index].appendChild(input);
 
    //Clear the TextBox.
    textbox.value = "";
}
</script>
 
 
Inserting the GridView Rows to database Table
The following event handler is executed when the Submit button is clicked it first fetches the values of the Name and the Country HiddenFields from the Request.Form collection and then inserts each Name and Country pair to the database.
C#
protected void Submit(object sender, EventArgs e)
{
    if (!string.IsNullOrEmpty(Request.Form["name"]) && !string.IsNullOrEmpty(Request.Form["country"]))
    {
        //Fetch the Hidden Field values from the Request.Form collection.
        string[] names = Request.Form["name"].Split(',');
        string[] countries = Request.Form["country"].Split(',');
 
        //Loop through the values and insert into database table.
        for (int i = 0; i < names.Length; i++)
        {
            string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand("INSERT INTO Customers VALUES(@Name, @Country)"))
                {
                    cmd.Parameters.AddWithValue("@Name", names[i]);
                    cmd.Parameters.AddWithValue("@Country", countries[i]);
                    cmd.Connection = con;
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();
                }
            }
        }
 
        //Refresh the page to load GridView with records from database table.
        Response.Redirect(Request.Url.AbsoluteUri);
    }
}
 
VB.Net
Protected Sub Submit(sender As Object, e As EventArgs)
    If Not String.IsNullOrEmpty(Request.Form("name")) AndAlso Not String.IsNullOrEmpty(Request.Form("country")) Then
        'Fetch the Hidden Field values from the Request.Form collection.
        Dim names As String() = Request.Form("name").Split(",")
        Dim countries As String() = Request.Form("country").Split(",")
 
        'Loop through the values and insert into database table.
        For i As Integer = 0 To names.Length - 1
            Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
            Using con As New SqlConnection(constr)
                Using cmd As New SqlCommand("INSERT INTO Customers VALUES(@Name, @Country)")
                    cmd.Parameters.AddWithValue("@Name", names(i))
                    cmd.Parameters.AddWithValue("@Country", countries(i))
                    cmd.Connection = con
                    con.Open()
                    cmd.ExecuteNonQuery()
                    con.Close()
                End Using
            End Using
        Next
 
        'Refresh the page to load GridView with records from database table.
        Response.Redirect(Request.Url.AbsoluteUri)
    End If
End Sub
 
The following screenshot displays the inserted record
Dynamically Add Rows to GridView using JavaScript on Button Click in ASP.Net
 
Screenshot
Dynamically Add Rows to GridView using JavaScript on Button Click in ASP.Net
 
 
Browser Compatibility

The above code has been tested in the following browsers.

Internet Explorer  FireFox  Chrome  Safari  Opera 

* All browser logos displayed above are property of their respective owners.

 
 
Demo
 
 
Downloads

GridView_AddRow_JavaScript.zip