Click here to Skip to main content
6,596,602 members and growing! (20,350 online)
Email Password   helpLost your password?
Web Development » Ajax and Atlas » Controls     Intermediate

Client Side Paging in DataGrid (AjaxGrid)

By Russell Aboobacker

Client side paging in DataGrid.
C#, Javascript, XML, HTML, Windows, .NET 1.1, ASP.NET, Ajax, VS.NET2003, Dev
Posted:12 Sep 2005
Views:86,144
Bookmarked:70 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
14 votes for this article.
Popularity: 3.32 Rating: 2.90 out of 5
5 votes, 35.7%
1

2
2 votes, 14.3%
3
2 votes, 14.3%
4
5 votes, 35.7%
5

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

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

/////////////////////////////////////////////////////////////////

//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>
  <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

About the Author

Russell Aboobacker


Member
Russell Aboobacker is a Software Engineer from India, Currently working in First Indian Corp Bangalore as Senior Software Engineer. He Enjoys Coding and Sharing his Experience with the Colleagues and Friends.When he is not coding he enjoys spending time with his Beloved Wife and Son.

If you have any suggestions / Ideas , Share it With me. arussel@firstam.com
Occupation: Web Developer
Location: India India

Other popular Ajax and Atlas articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 13 of 13 (Total in Forum: 13) (Refresh)FirstPrevNext
Questioncreating common datagrid function Pinmember2:28 21 Mar '07  
AnswerRe: creating common datagrid function PinmemberGanesan Sankaran23:45 23 Jan '08  
GeneralFiltering Datagrid in Asp.net 2003 using client side Pinmemberpragnesh_baps19:03 19 Feb '07  
Jokehttp://vardenafil.tangoing.info/ Pinsusshttp://vardenafil.tangoing.info/16:53 4 Dec '07  
GeneralIt will not work when the Datagrid Sorting Expression is on PinmemberChintan Jariwala23:10 26 Oct '06  
GeneralIt will not work when the Datagrid Sorting Expression is on PinmemberChintan Jariwala23:08 26 Oct '06  
GeneralThis project is not runing in Mozilla Firefox help me! Pinmemberdoancongxd970718:39 21 Oct '06  
GeneralAjax Projects PinmemberHazem Torab11:57 4 Jan '06  
Generalyou stole my article :( PinmemberTaha Zayed2:01 20 Nov '05  
GeneralNeed more features Pinmemberdanielprc3:09 14 Oct '05  
NewsGood One PinmemberPragat3:10 20 Sep '05  
GeneralBrilliance and catastrophie Pinmemberrobrich21:25 12 Sep '05  
GeneralGood Stuff PinmemberSendilkumar.M17:55 12 Sep '05  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 12 Sep 2005
Editor: Smitha Vijayan
Copyright 2005 by Russell Aboobacker
Everything else Copyright © CodeProject, 1999-2009
Web19 | Advertise on the Code Project