Click here to Skip to main content
15,881,898 members
Articles / Web Development / HTML
Article

Client Side Paging in DataGrid (AjaxGrid)

Rate me:
Please Sign up or sign in to vote.
3.15/5 (15 votes)
12 Sep 20052 min read 118K   701   76   13
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


Written By
Web Developer
India India
Russell Aboobacker is a Software Engineer from India, Currently working in Cognizant, Bangalore as Software Architect. He Enjoys Coding and Sharing his Experiences with the Colleagues and Friends.When he is not coding he enjoys spending time with his Family.

If you have any suggestions / Ideas , Share it With me. arusselkm@yahoo.com

Comments and Discussions

 
Questioncreating common datagrid function Pin
Member 391760021-Mar-07 1:28
Member 391760021-Mar-07 1:28 
AnswerRe: creating common datagrid function Pin
Ganesan Sankaran23-Jan-08 22:45
Ganesan Sankaran23-Jan-08 22:45 
GeneralFiltering Datagrid in Asp.net 2003 using client side Pin
pragnesh_baps19-Feb-07 18:03
pragnesh_baps19-Feb-07 18:03 
Jokehttp://vardenafil.tangoing.info/ Pin
http://vardenafil.tangoing.info/4-Dec-07 15:53
susshttp://vardenafil.tangoing.info/4-Dec-07 15:53 
GeneralIt will not work when the Datagrid Sorting Expression is on Pin
Chintan Jariwala26-Oct-06 22:10
Chintan Jariwala26-Oct-06 22:10 
GeneralIt will not work when the Datagrid Sorting Expression is on Pin
Chintan Jariwala26-Oct-06 22:08
Chintan Jariwala26-Oct-06 22:08 
GeneralThis project is not runing in Mozilla Firefox help me! Pin
doancongxd970721-Oct-06 17:39
doancongxd970721-Oct-06 17:39 
GeneralAjax Projects Pin
Hazem Torab4-Jan-06 10:57
Hazem Torab4-Jan-06 10:57 
Generalyou stole my article :( Pin
Taha Elsayed20-Nov-05 1:01
Taha Elsayed20-Nov-05 1:01 
GeneralNeed more features Pin
KeithPRC14-Oct-05 2:09
KeithPRC14-Oct-05 2:09 
NewsGood One Pin
Member 199197520-Sep-05 2:10
Member 199197520-Sep-05 2:10 
GeneralBrilliance and catastrophie Pin
robrich12-Sep-05 20:25
robrich12-Sep-05 20:25 
GeneralGood Stuff Pin
Sendilkumar.M12-Sep-05 16:55
Sendilkumar.M12-Sep-05 16:55 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.