In this article I will explain how to dynamically add rows to GridView on client side using jQuery on Button click in ASP.Net.
The GridView Rows added using jQuery 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.
Note: You can download the database table SQL by clicking the download link below.
HTML Markup
The following HTML Markup consists of an ASP.Net GridView, two TextBoxes and two Buttons. The Add button is assigned a jQuery click event handler (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" />
</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 jQuery.
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 jQuery on Button Click
When the Add Button is clicked, the following jQuery click event handler is executed. Inside this event handler, first the GridView is referenced.
Note: The GridView is rendered as HTML Table in browser.
Then the first Row of the GridView is referenced in a jQuery 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 jQuery.
Finally the row is appended to the GridView.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("[id*=btnAdd]").click(function () {
//Reference the GridView.
var gridView = $("[id*=gvCustomers]");
//Reference the first row.
var row = gridView.find("tr").eq(1);
//Check if row is dummy, if yes then remove.
if ($.trim(row.find("td").eq(0).html()) == "") {
row.remove();
}
//Clone the reference first row.
row = row.clone(true);
//Add the Name value to first cell.
var txtName = $("[id*=txtName]");
SetValue(row, 0, "name", txtName);
//Add the Country value to second cell.
var txtCountry = $("[id*=txtCountry]");
SetValue(row, 1, "country", txtCountry);
//Add the row to the GridView.
gridView.append(row);
return false;
});
function SetValue(row, index, name, textbox) {
//Reference the Cell and set the value.
row.find("td").eq(index).html(textbox.val());
//Create and add a Hidden Field to send value to server.
var input = $("<input type = 'hidden' />");
input.prop("name", name);
input.val(textbox.val());
row.find("td").eq(index).append(input);
//Clear the TextBox.
textbox.val("");
}
});
</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
Screenshot
Demo
Downloads
Download Code