Search - Articles
DevASP.NET for ASP.NET, VB.NET, XML and C# (C-Sharp) Developers Tuesday, March 03, 2009
Dev Articles
Search Directory
ASP.NET
VB.Net
C-Sharp
SQL Server
 

How to bind data to GridView using JQuery and WebMethod in ASP.NET

Author: Rachel Nicole
Download Source Code : 1407_BindGridViewUsingJQuery.zip

The purpose of this article is to explain how we can bind data to GridView control using jQuery and WebMethod in ASP.NET.

 

Binding data to GridView control using jQuery and WebMethod is simple. We can simply create a DataTable object, add column names to it and bind it GridView without any data. WebMethod can be used to get data from and jQuery can be used to bind it to GridView. We can bind data to GridView on page load or on a button click event using jQuery. It is entirely up to us that where we want to bind our data to GridView using jQuery.
 
  1. Open Visual Studio 2010
  2. File > New > Web Site
  3. Visual Basic or Visual C# > ASP.NET Empty Web Site
  4. Right click on web site > Add New Item > Web Form
  5. Right click on website > New Folder (Name the folder as “Scripts”). Download jQuery and jQuery autocomplete plug-in and include below files in this folder.

    jquery-1.4.1.min.js
     
  6. Right click on web site > Add New Item > Class (Name the class as Products.cs or Products.vb)
  7. Add a code below in Products.cs or Products.vb

    C#
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Data;
    using System.Data.SqlClient;
     
    ///
    /// Summary description for Products
    ///
    public class Products
    {
        private int prodID = 0;
        private string prodName = "";
        private decimal unitPrice = 0;
     
        public int ProductID
        {
            set
            {
                this.prodID = value;
            }
            get
            {
                return this.prodID;
            }
        }
        public string ProductName
        {
            set
            {
                this.prodName = value;
            }
            get
            {
                return this.prodName;
            }
        }
        public decimal UnitPrice
        {
            set
            {
                this.unitPrice = value;
            }
            get
            {
                return this.unitPrice;
            }
        }
     
        public static DataTable ProductsData()
        {
            string cmdText = "SELECT ProductID, ProductName, UnitPrice FROM Products WHERE UnitPrice <= 10";
            string myConnection = "Data Source=local;Initial Catalog=NORTHWND;Integrated Security=True";
            SqlConnection connection = new SqlConnection(myConnection);
            SqlCommand command = new SqlCommand(cmdText, connection);
            SqlDataAdapter adapter = new SqlDataAdapter(command);
            DataTable table = new DataTable();
            adapter.Fill(table);
            connection.Close();
            return table;
        }
    }
     
    VB.NET
     
    Imports Microsoft.VisualBasic
    Imports System.Data
    Imports System.Data.SqlClient
     
    Public Class Products
        Private prodID As Integer = 0
        Private prodName As String = ""
        Private untPrice As Decimal = 0
     
        Public Property ProductID() As Integer
            Get
                Return Me.prodID
            End Get
            Set(value As Integer)
                Me.prodID = value
            End Set
        End Property
        Public Property ProductName() As String
            Get
                Return Me.prodName
            End Get
            Set(value As String)
                Me.prodName = value
            End Set
        End Property
        Public Property UnitPrice() As Decimal
            Get
                Return Me.untPrice
            End Get
            Set(value As Decimal)
                Me.untPrice = value
            End Set
        End Property
     
        Public Shared Function ProductsData() As DataTable
            Dim cmdText As String = "SELECT ProductID, ProductName, UnitPrice FROM Products WHERE UnitPrice <= 10"
            Dim myConnection As String = "Data Source=local;Initial Catalog=NORTHWND;Integrated Security=True"
            Dim connection As New SqlConnection(myConnection)
            Dim command As New SqlCommand(cmdText, connection)
            Dim adapter As New SqlDataAdapter(command)
            Dim table As New DataTable()
            adapter.Fill(table)
            connection.Close()
            Return table
        End Function
    End Class
     
    I have created a class, declared private variables and set their properties. I have created a function that gets data from Products table of NORTHWND database and returns DataTable. Make sure that this function is declared as public static in case of C# or public shared in case of Vb.NET.  

     
  8. Now write code below in code behind file of Default.aspx.cs or Default.aspx.vb

    C#
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.Services;
    using System.Data;
    using System.Data.SqlClient;
     
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
            DataColumn c1 = new DataColumn("ProductID");
            DataColumn c2 = new DataColumn("ProductName");
            DataColumn c3 = new DataColumn("UnitPrice");
            dt.Columns.Add(c1);
            dt.Columns.Add(c2);
            dt.Columns.Add(c3);
           
            GridView1.DataSource = dt;
            GridView1.DataBind();
     
        }
     
        [WebMethod]
        public static List GetProducts()
        {
            DataTable table = Products.ProductsData();
     
            List list = new List();
     
            foreach (DataRow row in table.Rows)
            {
                Products detail = new Products();
                detail.ProductID = Convert.ToInt32(row["ProductID"]);
                detail.ProductName = row["ProductName"].ToString();
                detail.UnitPrice = Convert.ToDecimal(row["UnitPrice"]);
                list.Add(detail);
            }
            return list;
        }
    }
     
    VB.NET

    Imports System.Data
    Imports System.Web.Services
     
    Partial Class _Default
        Inherits System.Web.UI.Page
     
        Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
            Dim dt As New DataTable()
            Dim c1 As New DataColumn("ProductID")
            Dim c2 As New DataColumn("ProductName")
            Dim c3 As New DataColumn("UnitPrice")
            dt.Columns.Add(c1)
            dt.Columns.Add(c2)
            dt.Columns.Add(c3)
     
            GridView1.DataSource = dt
            GridView1.DataBind()
        End Sub

        <WebMethod()> _
        Public Shared Function GetProducts() As List(Of Products)
            Dim table As DataTable = Products.ProductsData()
     
            Dim list As New List(Of Products)()
     
            For Each row As DataRow In table.Rows
                Dim detail As New Products()
                detail.ProductID = Convert.ToInt32(row("ProductID"))
                detail.ProductName = row("ProductName").ToString()
                detail.UnitPrice = Convert.ToDecimal(row("UnitPrice"))
                list.Add(detail)
            Next
            Return list
        End Function
    End Class
     
    In page load method of code behind file, I have created a DataTable object, added columns to it and provided this DataTable object to GridView control as DataSource without any data. I have created a WebMethod that returns a list of Products class. I have retrieved values from ProductsData() method and added it to Products class list object.
     
  9. Now time to add client side code. Add code below in Default.aspx page

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
     
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
     
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <script type="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function () {
                $("#Button1").click(function () {
                    $.ajax({
                        type: "POST",
                        url: "Default.aspx/GetProducts",
                        data: "{}",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (r) {
                            for (var i = 0; i < r.d.length; i++) {
                                $("#GridView1").append("<tr><td>" + r.d[i].ProductID +
                                        "</td><td>" + r.d[i].ProductName +
                                        "</td><td>" + r.d[i].UnitPrice + "</td></tr>");
                            }
                        }
                    });
                });
            });
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <input id="Button1" type="button" value="Bind GridView using JQuery" />
            <asp:GridView ID="GridView1" ShowHeaderWhenEmpty="true" runat="server">
            </asp:GridView>
        </div>
        </form>
    </body>
    </html>
     
    As you can see I have added a button and a GridView control in the page and set ShowHeaderWhenEmpty property to true. I have used a “for” loop to get data from WebMethod and added row and cell tags.
     
  10. Now see it in your browser.

 

   
Add Article Comment:
Name :
Email Address :
   
Comments :
 
   
<< ExecuteReader, ExecuteScalar and ExecuteNonQuery methods in ASP.NET

Disclaimer - Privacy
© 2002-2017 DevASP.net