In this article I will explain with an example, how to populate (bind) DataSet to GridView using jQuery AJAX in ASP.Net
with C# and VB.Net.
This article will illustrate how to populate
GridView control from
SQL Server database on Client Side by calling
WebMethod using
jQuery AJAX in C# and VB.Net.
Database
Here I am making use of Microsoft’s Northwind Database. You can download it from here.
HTML Markup
The HTML Markup consists of following controls:
GridView – For displaying data.
Columns
The GridView consists of three BoundField columns.
<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="CustomerID" HeaderText="Customer Id" />
<asp:BoundField DataField="ContactName" HeaderText="ContactName" />
<asp:BoundField DataField="Country" HeaderText="Country" />
</Columns>
</asp:GridView>
Binding Dataset to GridView using jQuery AJAX
Inside the HTML, following script file is inherited.
1. jquery.min.js
Inside the
OnSuccess JavaScript event handler, the XML string is parsed into an XML document and then a FOR EACH loop is executed for each entry present in the XML.
Inside the FOR EACH loop, the columns of GridView control is cloned and values are set to their respective fields.
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$.ajax({
type: "POST",
url: "Default.aspx/GetCustomers",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (r) {
alert(r.d);
},
error: function (response) {
alert(r.d);
}
});
});
function OnSuccess(r) {
//Parse the XML and extract the records.
var customers = $($.parseXML(r.d)).find("Table");
//Reference GridView Table.
var table = $("[id*=gvCustomers]");
//Reference the Dummy Row.
var row = table.find("tr:last-child").clone(true);
//Remove the Dummy Row.
$("tr", table).not($("tr:first-child", table)).remove();
//Loop through the XML and add Rows to the Table.
$.each(customers, function () {
var customer = $(this);
$("td", row).eq(0).html($(this).find("CustomerID").text());
$("td", row).eq(1).html($(this).find("ContactName").text());
$("td", row).eq(2).html($(this).find("Country").text());
table.append(row);
row = table.find("tr:last-child").clone(true);
});
}
</script>
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
Binding the GridView
Inside the Page_Load event handler, the GridView is populated with dynamic DataTable.
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dtCustomers = new DataTable();
dtCustomers.Columns.Add("CustomerID");
dtCustomers.Columns.Add("ContactName");
dtCustomers.Columns.Add("Country");
dtCustomers.Rows.Add();
gvCustomers.DataSource = dtCustomers;
gvCustomers.DataBind();
}
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Dim dtCustomers As DataTable = New DataTable()
dtCustomers.Columns.Add("CustomerID")
dtCustomers.Columns.Add("ContactName")
dtCustomers.Columns.Add("Country")
dtCustomers.Rows.Add()
gvCustomers.DataSource = dtCustomers
gvCustomers.DataBind()
End If
End Sub
WebMethod (PageMethod) to handle jQuery AJAX call
Inside the
WebMethod, the records are fetched from the
Customers Table of the
SQL Server database and populates
DataSet using
SqlDataAdapter.
Finally,
DataSet is returned as an XML string.
Note: The following
WebMethod is declared as
static (C#) and
Shared (VB.Net), it is decorated with
WebMethod attribute, this is necessary otherwise the method will not be called from client side
jQuery AJAX call.
C#
[WebMethod]
public static string GetCustomers()
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
string sql = "SELECT TOP 10 CustomerID, ContactName, Country FROM Customers";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlDataAdapter sda = new SqlDataAdapter(sql, con))
{
using (DataSet ds = new DataSet())
{
sda.Fill(ds);
return ds.GetXml();
}
}
}
}
VB.Net
<WebMethod>
Public Shared Function GetCustomers() As String
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Dim sql As String = "SELECT TOP 10 CustomerID, ContactName, Country FROM Customers"
Using con As SqlConnection = New SqlConnection(constr)
Using sda As SqlDataAdapter = New SqlDataAdapter(sql, con)
Using ds As DataSet = New DataSet()
sda.Fill(ds)
Return ds.GetXml()
End Using
End Using
End Using
End Function
Screenshot
Browser Compatibility
* All browser logos displayed above are property of their respective owners.
Demo
Downloads