Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

Client Side Paging in DataGrid (AjaxGrid)

3.15/5 (15 votes)
12 Sep 20052 min read 2   701  
Client side paging in DataGrid.

Sample Image - AjaxGrid.gif

Introduction

AjaxGrid offers you an efficient and easy way to implement client side paging. It uses a Web Service called by the client script using AJAX technology.

This idea was inspired by an article posted in CodeProject. I went through it and found that an HTML table is produced by the client script by parsing an XML dataset.

And instead of generating a single page it generates all the pages in separate layers and hides all the other layers except the current page layer. It’s an interesting way, but for implementing this way of paging there is no need of AJAX, since the generation of all the HTML is at once. No further interaction between the client and the server is happening.

Then it came to my head, “Why don’t we use the DataGrid class of Microsoft for the generation of the HTML table with the data?” Since we have a handy and powerful class like the DataGrid why should we generate the HTML manually and go back in technology?

Yes was the answer, so I went to the next step, the implementation. Aha!!! It was so easy!! Believe me. I just wrote a Web Service which returns the HTML of a DataGrid by parsing it using the RenderControl method. And then I added some more code to implement paging.

GenericAjaxWS.asmx.cs

C#
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Web;
using System.Web.Services;
using System.Configuration;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.IO;

namespace GenricAjaxWS
{
      [WebService(Namespace="http://localhost/GenricAjaxWS/")]
      public class GenricAjaxWS : System.Web.Services.WebService
      {
            SqlConnection con;
            SqlDataAdapter da;
            SqlCommand cmd;
            DataSet ds;

            public GenricAjaxWS()
            {
              InitializeComponent();
              con= new SqlConnection(ConfigurationSettings.AppSettings["Connect"]);
              da=new SqlDataAdapter("",con);
              cmd=new SqlCommand("",con);
              ds=new DataSet("TahaSchema");
            }

            #region Component Designer generated code

            //Required by the Web Services Designer 
            private IContainer components = null;

            /// <summary>
            /// Required method for Designer support - do not modify
            /// the contents of this method with the code editor.
            /// </summary>
            private void InitializeComponent()
            {
            }

            /// <summary>
            /// Clean up any resources being used.
            /// </summary>
            protected override void Dispose( bool disposing )
            {
              if(disposing && components != null)
              {
                    components.Dispose();
              }
              base.Dispose(disposing);
            }
            
            #endregion
 
/// <summary>
/// this function accepts TSql statment and returns dataset
/// </summary>
 

            [WebMethod]
            public string getGrid(string sqlStr,int pageIndex)
            {
              da.SelectCommand.CommandText=sqlStr;
              da=new SqlDataAdapter(sqlStr,con);
              da.Fill(ds,"myTable");

              DataGrid dataGrid = new DataGrid();
              dataGrid.AutoGenerateColumns = true;
              dataGrid.DataSource = ds.Tables["myTable"].DefaultView;
              dataGrid.AllowPaging = true;
              dataGrid.PageSize = 4;
              dataGrid.PagerStyle.Visible = false;
              dataGrid.CurrentPageIndex = pageIndex;
              try
              {
                    dataGrid.DataBind();
              }
              catch(Exception)
              {

              }
              StringWriter wr = new StringWriter();
              HtmlTextWriter writer = new HtmlTextWriter(wr);
              dataGrid.RenderControl(writer);
              string gridHtml = wr.ToString();
              wr.Close();
              writer.Close();
              DropDownList ddl_Pager = new DropDownList();
              ddl_Pager.Attributes.Add("onchange","goToPage(this.value)");
              string pager="";
              for(int i=0;i<dataGrid.PageCount;i++)
              {
                ListItem lItem = new ListItem(i.ToString(),i.ToString());
                ddl_Pager.Items.Add(lItem);
                if(i==pageIndex)
                {
                  pager += "[<span style=\"background-color:#ffdd11;width" + 
                         ":20px;align:center\"><a href=\"#\" onclick" + 
                         "=\"goToPage('"+i+"')\">"+i+"</a></span>]";
                }
                else
                {
                  pager += "[<span style=\"width:20px;align:center\">" + 
                         "<a href=\"#\" onclick=\"goToPage" + 
                         "('"+i+"')\" >"+i+"</a></span>]";
                }
              }
              ddl_Pager.SelectedIndex = pageIndex;
              wr = new StringWriter();
              writer = new HtmlTextWriter(wr);
              ddl_Pager.RenderControl(writer);
              string pagerHtml = "<input type='button'" + 
                                 " value='<' onclick='goToPrevPage()'>";
              pagerHtml += wr.ToString();
              pagerHtml += "<input type='button' value='>'" + 
                           " onclick='this.disabled=goToNextPage()'>";
              wr.Close();
              writer.Close();
              return pager+pagerHtml+"<br>"+gridHtml;
            }
      }
}

We have written the Web Service….The next step is to communicate with the Service from the client script. Here comes AJAX for your help. First of all deploy the Web Service and start a new project called AjaxGridTest. Add a JavaScript file called AjaxFuncs.js to the project.

AjaxFuncs.js

JavaScript
/////////////////////////////////////////////////////////////////
//Variable Declarations
/////////////////////////////////////////////////////////////////
var xmlhttp;
/////////////////////////////////////////////////////////////////
//fillGrid
//This Function Takes three parameters
//first parameter is the id of a DIV tag to which you want 
//to populate the Grid
//Second Paramaeter is the Sql String
//Third Parameter is the selected page index
/////////////////////////////////////////////////////////////////
var ph;
var fillGrid_Str_SQL="";
var currentPageIndex ;
function fillGrid(myPH,str_Sql,pageIndex){
      ph = window.document.getElementById(myPH);
      fillGrid_Str_SQL = str_Sql;
      currentPageIndex = pageIndex;
      var url = "http://localhost/GenricAjaxWS/GenricAjaxWS" + 
                ".asmx/getGrid?sqlStr="+str_Sql+
                "&pageIndex="+pageIndex;

      if(window.XMLHttpRequest)
    {
        xmlhttp=new XMLHttpRequest();
        xmlhttp.onreadystatechange=fillGrid_Change;
        xmlhttp.open("GET",url,true);
        xmlhttp.send(null);
    }
    //code for IE
    else if (window.ActiveXObject)
        {
        try
            {
            xmlhttp= new ActiveXObject("Msxml2.XMLHTTP");
            }
        catch(e)
            {
            try
            {
                xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch(e){}
        }

        if(xmlhttp)
        {
            try
            {
            xmlhttp.onreadystatechange=fillGrid_Change;
            xmlhttp.open("GET",url,false);
            xmlhttp.send();
            }
            catch(e){}
        }
    } 
}
/////////////////////////////////////////////////////////////
//fillGrid_Change
/////////////////////////////////////////////////////////////
function fillGrid_Change()
{
      if(xmlhttp.readyState==4&&xmlhttp.status==200)
      {
          //var rows=xmlhttp.responseXML.
          //        selectNodes(".//TahaSchema//TahaTable");
          var row =   xmlhttp.responseXML.selectNodes(".//");
          ph.innerHTML = row[1].text;
      }
}

function goToPage(pageIndex){
      fillGrid(ph.id,fillGrid_Str_SQL,pageIndex)
}
 
function goToNextPage(){
      try{  
            fillGrid(ph.id,fillGrid_Str_SQL, 
                     parseInt(currentPageIndex)+1);
            return false;
      }
      catch(e){
            return true;
      }
}

function goToPrevPage(){
      fillGrid(ph.id,fillGrid_Str_SQL,
               parseInt(currentPageIndex)-1)
}

Now add a page AjaxGrid.html to the project.

AjaxGrid.html

HTML
<html>
  <head>
    <title>AjaxGrid</title>
  <script language="javascript" 
        type="text/javascript" src="ajaxFuncs.js"></script>
  </head>
  <body  onload="fillGrid('myPH','select * from sales',1)">
            
    <form id="Form1" method="post" runat="server">
                        <div id="myPH" ></div>
     </form>
  </body>
</html>

That’s all !!!

You have successfully developed a DataGrid with client side paging. Hope that this article helped you to learn something. Please write to me regarding any comments / suggestions.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here