Bind Data to GridView Using jQuery

This article explains how to bind data to a GridView using jQuery.

Introduction

This article explains how to bind data to a GridView using jQuery.

Sometimes before I need to show some data in a grid but not show the redirected page on any type of click obviously I choose jQuery. I bind the data to the GridView using Ajax calls and jQuery.

If you inspect the GridView in your browser then you must have noticed that the GridView has <th>, <tr> and <td> tags to show the data so I used this technique to bind the data to the Grid :).

Step 1

First of all I create some checkboxes on which the Grid needs to be bound, on each new click the new data is to be shown. So here I am simply creating some checkboxes for examples.

  1. <table>  
  2.   <tr>  
  3.     <td>  
  4.       <div id="div1" style="width: 170px; height: 160px;">  
  5.         <asp:CheckBox ID="chk1" runat="server" />  
  6.         <asp:Label ID="lbl" runat="server" Text=":Legal Status Report" AssociatedControlID="chk1"></asp:Label>  
  7.         <hr />  
  8.          Category:  
  9.    <br />  
  10.         <asp:CheckBox runat="server" ID="chk2" />  
  11.           :Fresh Recognition  
  12.    <br />  
  13.         <asp:CheckBox runat="server" ID="chk3" />  
  14.           :Renewal Recognition  
  15.    <br />  
  16.         Legal Status Category:  
  17.    <br />  
  18.          <asp:DropDownList ID="drp2" Width="100px" runat="server">  
  19.             <asp:ListItem Text="Select" Selected="True"></asp:ListItem>  
  20.             <asp:ListItem Text="Item1"></asp:ListItem>
  21.          </asp:DropDownList>  
  22.       </div>  
  23.      </td>  
  24.    </tr>  
  25. </table> 

Now I add a GridView that is to be bound on different clicks:

  1. <asp:GridView ID="grd" runat="server" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2">  
  2.     <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />  
  3.     <HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />  
  4.     <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />  
  5.     <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />  
  6.     <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />  
  7.     <SortedAscendingCellStyle BackColor="#FFF1D4" />  
  8.     <SortedAscendingHeaderStyle BackColor="#B95C30" />  
  9.     <SortedDescendingCellStyle BackColor="#F1E5CE" />  
  10.     <SortedDescendingHeaderStyle BackColor="#93451F" />  
  11. </asp:GridView> 

Step 2

Now our jQuery work begins. First of all add a jQuery library so that our jQuery code can work otherwise it will give you an error something like "$ is not defined" and this error can only be seen in the console so don't try to find it in the UI.

Just add this line and your jQuery will start working:

  1. <script src="//code.jquery.com/jquery-1.10.2.js"></script> 

Now I wrote the following code for the click of the first checkbox:

  1.  <script>  
  2.      $(document).ready(function () {  
  3.          $('#chk1').click(function () {  
  4.                  $('#grd').empty();  
  5.                  load_Data();  
  6.              }  
  7.          })  
  8.        });  
  9. </script> 

Here I call the function load_Data(). In this function the Ajax call is made for a web method that is on the aspx.cs page:

  1. function load_Data() {  
  2.     debugger;  
  3.     $.ajax({  
  4.         type: 'POST',  
  5.         contentType: "application/json; charset=utf-8",  
  6.         url: 'WebForm2.aspx/Get_Data',  
  7.         data: "{}",  
  8.         dataType: 'JSON',  
  9.         success: function (response) {
  10.             $('#grd').append("<tr><th>Recognition_Type </th><th>Recognition_Number </th></tr>")  
  11.             for (var i = 0; i < response.d.length; i++) {  
  12.                 debugger;  
  13.                 $('#grd').append("<tr><td>" + response.d[i].Recognition_Type + "</td><td>" + response.d[i].Recognition_Number + "</td></tr>")  
  14.             };  
  15.   
  16.         },  
  17.         error: function () {  
  18.   
  19.             alert("Error");  
  20.         }  
  21.     });  
  22.     return false;  
  23. }; 

In the code behind web method a simple SQL connection is made for retrieving some data from a table named "testReport". From this data a list is created that is returned to the Ajax success function.

  1. [WebMethod]  
  2. public static List<Info> Get_Data()  
  3. {  
  4.     SqlConnection conn = new SqlConnection(@"your connection");  
  5.     DataTable dt = new DataTable();  
  6.       
  7.     conn.Open();  
  8.     SqlCommand cmd = new SqlCommand("select * from testReport", conn);  
  9.     cmd.CommandType = CommandType.Text;  
  10.     var d = cmd.ExecuteReader();  
  11.     dt.Load(d);  
  12.     List<Info> list = new List<Info>();  
  13.     Info info;  
  14.     foreach (DataRow dr in dt.Rows)  
  15.     {  
  16.         info = new Info(dr["Recognition_Type"].ToString(), dr["Recognition_No"].ToString());  
  17.         list.Add(info);  
  18.     }  
  19.     conn.Close();  
  20.     return list;  
  21. }  
  22.   
  23. public class Info  
  24. {  
  25.     public Info(string recognition_type, string recognition_number)  
  26.     {  
  27.         this.Recognition_Type = recognition_type;  
  28.         this.Recognition_Number = recognition_number;  
  29.     }  
  30.     private string _type;  
  31.     private string _number;  
  32.     public string Recognition_Type  
  33.     {  
  34.         get { return _type; }  
  35.         set { _type = value; }  
  36.     }  
  37.     public string Recognition_Number  
  38.     {  
  39.         get { return _number; }  
  40.         set { _number = value; }  
  41.     }  

 Step 3

When the list is returned it goes into the success function otherwise when an error occurs it will g into the error function.

On reaching the success function some headings are appended to the GridView because it works like a table on the UI.

After this data is recieved it is append to the columns of the GridView.

  1. success: function (response) {  
  2.     $('#grd').append("<tr><th>Recognition_Type </th><th>Recognition_Number </th></tr>")  
  3.     for (var i = 0; i < response.d.length; i++) {
  4.         $('#grd').append("<tr><td>" + response.d[i].Recognition_Type + "</td><td>" + response.d[i].Recognition_Number + "</td></tr>")  
  5.     };  
  6.   
  7. },  
  8. error: function () {  
  9.     alert("Error");  

Step 4

Now if some other checkbox is checked then a new function is called named "load_Fresh_Data()" but before calling this function the Grid is made empty so that new data can be bound to the Grid.

  1. $('#CheckBox1').click(function () {  
  2.         $('#grd').empty();  
  3.         load_RND_Data();  
  4.     }); 

In this new function again the same procedure executes, in other words again an Ajax call is made, again a SQL connection is created and some data is fetched, a list is returned to the success function that is bound to the columns of the GridView otherwise an error message is shown.

  1. function load_RND_Data() {    
  2.     $.ajax({    
  3.         type: 'POST',    
  4.         contentType: "application/json; charset=utf-8",    
  5.         url: 'WebForm2.aspx/load_RND_Data',    
  6.         data: "{}",    
  7.         dataType: 'JSON',    
  8.         success: function (response) {    
  9.             $('#grd').append("<tr><th>Company_Name </th><th>Legal_Status_Category </th></tr>")    
  10.             for (var i = 0; i < response.d.length; i++) {    
  11.                 $('#grd').append("<tr><td>" + response.d[i].Company_Name + "</td><td>" + response.d[i].Legal_Status_Category + "</td></tr>")    
  12.             };    
  13.     
  14.         },    
  15.         error: function () {    
  16.             alert("Error");    
  17.         }    
  18.     });    
  19.     return false;    
  20. };   
Output
 
On running the  application I click the first checkbox and get an output like this one:
 
Bind GridView through jQuery 
 On clicking the new checkbox the Grid will bound again with new data.
 
Bind GridView through jQuery