Ahmed Moosa

Nothing but ASP.Net

Bind Gridview using Jquery

 

What about working with database using client-side? How can I bind Grid View using client-side? How can I retrieve specific row or column using client-side? OK.

full Source Code :Click Here

In fact there is no Data Source property existing in Jquery, but keep in mind that grid view render as Html Table control, and this is the trick! we will append values returned from database as rows but we faced a problem , since the grid view doesn't has a DataSource or DataSourceID property we can't get it in Html , in other words if grid view doesn't have records [data] , it will not be rendered , therefore we can't find it in html source when page loaded. So we need to show empty grid view  to get it using Jquery selector .

another problem we have is how can we retrieve the data? What is the return type?

Actually jquery can't understand DataTable Object, DataSet or even DataReader .but already understand what array is ?,OK we get now that we will return an array but which data type "string , Integer , ......"?. well We did it! Let us start coding.

First step : Creating Data base which will be our data source ,we do it using building the following data table :

Datastore.cs

using System;
using System.Data;

public class DataStore
{
 public DataStore()
  {
    //
   // TODO: Add constructor logic here
  //
  }
 public static DataTable GetDataTable()
  {
   DataTable dt = new DataTable("Names");
   DataColumn dc1 = new DataColumn("Name");
   DataColumn dc2 = new DataColumn("Age");
   dt.Columns.AddRange(
new DataColumn[] { dc1, dc2 });
   DataRow dr1 = dt.NewRow();
   dr1[0] =
"Ahmed";
   dr1[1] =
"27";
   DataRow dr2 = dt.NewRow();
   dr2[0] =
"Peter";
   dr2[1] =
"30";
   DataRow dr3 = dt.NewRow();
   dr3[0] =
"John";
   dr3[1] =
"20";
   DataRow dr4 = dt.NewRow();
   dr4[0] =
"Ali";
   dr4[1] =
"30";
   dt.Rows.Add(dr1);
   dt.Rows.Add(dr2);
   dt.Rows.Add(dr3);
   dt.Rows.Add(dr4);

    return dt;
  }
}

Next step:

  • Creating Class file "Names" which will contain two properties (Data base columns) for "FirstName" and "Age". Like this :

Names.cs

public class Names
{
 public Names()
 {
   //
   // TODO: Add constructor logic here
  //
 }
 private string _firstName;
 private string _age;
 public string FirstName
 {
   set { _firstName = value; }
   get { return _firstName; }
 }
 public string Age
 {
   set { _age = value; }
   get { return _age; }
 }
}

Next Step:

  • Creating default.aspx page which will display and call the data.
  • Create GridView Control in your page :
    <div>
    <center>
        <br />
       
    <asp:GridView ID="NamesGridView" runat="server" ShowHeaderWhenEmpty="True" >
       
    </asp:GridView>
        <br />
    </center>
    </div>

Notice that we set ShowHeaderWhenEmpty property to true to display columns names when empty.

  • In page load event we will write some code which will display the gridview even it empty :

    protected void Page_Load(object sender, EventArgs e)
    {
      
    DataTable dt = new DataTable();
       dt.Columns.AddRange(
    new DataColumn[] { new DataColumn("Name"), new DataColumn("Age") });
      NamesGridView.DataSource = dt;
      NamesGridView.DataBind();
    }

Notice that we created two columns Names as "Name" and "Age" .Now you can run the page the GridView should be displayed (try it!).

  • In code behind we will create a method which will connect to datastore and retrieve the data values. As the following :


[WebMethod]
public static Names[] GetNames()
{
  List<Names> list = new List<Names>();
  DataTable dt = DataStore.GetDataTable();
 
foreach (DataRow row in dt.Rows)
  
{
     
Names _names = new Names();
     
_names.FirstName = row[
"Name"].ToString();
     
_names.Age = row[
"age"].ToString();
     
     
list.Add(_names);
  
}
  return list.ToArray();
}

Here we fill data values in the two properties (FirstName,Age) then we add it to List which accept Names Class Object as you saw above. And at the end we need to convert it to an array .

Notice that the method decorated with [Web Method] attribute which will allow us to get this method using client side code , and the method need to be declared as public and static also to get reached  outside the Container class .

Next Step :

  • - Calling Server side method that will get the data values and bind the gridview using Jquery like this :


<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
</
script>
<script type="text/javascript">
  function BindGridView() {
     $.ajax({
          type:
"POST",
          url:
"Default.aspx/GetNames",
          data:
"{}",
          contentType:
"application/json",
          dataType:
"json",
          success:
function (data) {
         for (var i = 0; i < data.d.length; i++) {
                $(
"#NamesGridView").append("<tr><td>" + data.d[i].FirstName + 
                                           
"</td><td>" + data.d[i].Age + "</td></tr>");
             }
           }
          })
      }
</script>

We can retrieve one column like "FirstName" or "Age" only, in the above code we create a loop to go through result data and using index of array element to get current row ,it is working like a datareader or dataset, then you get specific value "data.d[n].Age".

now ,we can call this functon on body load Like this :

<body onload="BindGridView();">
  <form id="form1" runat="server">
  
<div>
    
<center>
      
<br />
        
<asp:GridView ID="NamesGridView" runat="server" ShowHeaderWhenEmpty="True">
         
</asp:GridView>
      
<br />
    
</center>
   
</div>
 
</form>
</
body>

When we run this page it should Display GridView like this :

 

Happy programming

Ahmed Moosa

Comments

Twitter Trackbacks for Bind Gridview using Jquery - Ahmed Moosa [asp.net] on Topsy.com said:

Pingback from  Twitter Trackbacks for                 Bind Gridview using Jquery - Ahmed Moosa         [asp.net]        on Topsy.com

# October 31, 2010 1:33 AM

Grid is not showing said:

Hi,

I try this. But the grid is not displying. up to Appending the Items to grid is workig fine.

Regards,

Ak

# November 3, 2010 5:02 AM

ahmed moosa said:

@Grid is not showing  

Please follow steps and be sure that you are already call the BindGridView function like this line:

<body onload="BindGridView();">

Happy programming

Ahmed

# November 4, 2010 12:40 AM

Victor said:

Hola.

El ejemplo no esta funcionando?....

# November 5, 2010 7:24 AM

ahmed moosa said:

@Victor

Hola!

No, el ejemplo anterior funciona, puede descargarlo!

O desde aquĆ­ 

Gracias

# November 5, 2010 10:50 AM

dinesh said:

hi,

i am populating the grid view on button click .so pls.let me know how to do this.because if i call the bindGrid() fucntion on body load it will give an error saying"javascript object expected".

on page load i am dispaling a text box.i am entering some value in this text box and then  i am clinking the button on button click i want to display grid view.

# January 3, 2011 1:47 AM

nat06 said:

Hi Ahmed,

What if age column was a dropdownlist? How can I create an empty GridView if I have one column which is a DropDownList and want to add an add button at the end of the GridView like a separate column to be able to insert data from there? Can somebody help me please?

Thank you very much in advance.

# January 3, 2011 3:12 PM

Vincent said:

the Grid changes its style. It doesn't show exactly what i wanted. Like that in you last image(grid) the alternatingRowStyle is not working..

# January 7, 2011 10:26 PM

ravi said:

working nice...go and download

# July 29, 2011 9:19 AM

Javedboqo said:

Nice Article for begginers

# August 5, 2011 12:17 AM

doron said:

works when u change the grid to table

# August 27, 2011 9:58 AM

rbprajapati said:

Nice Article but how to use this code for the datalist and repeater?

# February 23, 2012 11:31 PM