Click here to Skip to main content
15,895,084 members
Articles / Web Development / ASP.NET

Paging of DataList, Repeater, or GridView

Rate me:
Please Sign up or sign in to vote.
3.86/5 (24 votes)
22 Apr 2008CPOL1 min read 43.8K   567   22   14
How to implement custom paging for DataList, Repeater, or GridView.

main_snap.JPG

Introduction

I have created a ControlPaging class to implement paging on the DataRepeater, DataList, and even on the DataGridView. The primary purpose of this tutorial is to facilitate the developer to implement paging in his/her controls without any difficulty by calling a few properties. A Utility assembly (Utility.dll) has been used for this purpose. The source files contains the source code of the assembly as well. You can modify this code in order to make it better. Please do point out any weakness or any areas where it can be made better.

Before we begin, let me tell explain the flow for implementing paging using the ControlPaging class. Here are the steps:

  1. Include the ControlPaging assembly in your application (in the Bin folder)
  2. Add the namespace SyedFasih above the code file (using SyedFasih;)
  3. Create an instance of the ControlPaging class (ControlPaging objPaging = new ControlPAging();)
  4. Set the PageIndex to the first page (objPaging.CurrentPageIndex = 0)
  5. Set the number of records you want to be displayed per page (objPaging.PageSize = 10)
  6. Set the DataSource of the ControlPaging instance (objPaging.DataSource=<DataTable>)

Now your paged data source is ready; you just have to set it as a data source of your control like:

C#
MyDataListControl.DataSource = objPaging;
MyDataListControl.DataBind();

Using the code

These are the basic steps for implementing paging on your control. Explanation of the code is included inline:

C#
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Data.OleDb;
using SyedFasih;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        DataTable dt = new DataTable();
        if (!IsPostBack)
        {
            Connection.GetDatabseFile = 
                Request.PhysicalApplicationPath.ToString()+@"\DB\Cartoon.mdb";
            OleDbConnection con = Connection.CreateConnection;
            OleDbCommand cmd = 
              new OleDbCommand("SELECT * FROM CartoonCharacters", con);
            OleDbDataAdapter da = new OleDbDataAdapter(cmd);
            da.Fill(dt);

            ControlPaging cpage = new ControlPaging();
            try
            {
                cpage.CurrentPageIndex = 0;     //Display the first Page
                cpage.PageSize = 6;             //Display Number of records per page
                cpage.DataSource = dt;          //Data Source 

                Session["DT"] = dt;             //Put Data Source into session for
                                                //further usage
                Session["CPAGE"] = cpage;       //Put ControlPaging instance into session
                                                //for further usage.

                BindList(cpage, dt);            //Binds the DataList Control with Data
                                                //using ControlPaging instance
            }
            catch (Exception)
            {

            }
            finally
            {
                cpage = null;  
            }
        }
    }

    void BindList(ControlPaging cpage, DataTable dt)
    {
        try
        {
            DLstCartoon.DataSource = cpage.DoPaging;        //Implement Paging by setting
                                                            //DataSource to ControlPaging
                                                            //DoPaging Property
            DLstCartoon.DataBind();                         //Databind the DataList

            lnkPrev.Enabled = !cpage.IsFirstPage;           //Enable / Disable Navigation
                                                            //Button
            lnkNext.Enabled = !cpage.IsLastPage;            //Enable / Disable Navigation
                                                            //Button

            lblPageStatus.Text = NavigationIndicator();    //Build Navigation Indicator
        }
        catch (Exception)
        {
        }
        finally
        {
            cpage = null;
        }
    }

    string NavigationIndicator()
    {
        string str  = string.Empty;     //Page x Of Y
        str = ((Convert.ToString((((
            ControlPaging)Session["CPAGE"]).CurrentPageIndex + 1)) + " Of " + ((
            ControlPaging)Session["cpage"]).PageCount.ToString()));
        return str;
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        ControlPaging cpage = (ControlPaging)Session["CPAGE"];
        //Gets ControlPaging instance from Session

        cpage.CurrentPageIndex = 0; //Refresh PageIndex
        Session["CPAGE"] = cpage; 
        //Put back ControlPaging instance to session with updated values

        try
        {
            cpage.PageSize = int.Parse(txtPageSize.Text);
            //Gets the PageSize given by the user

            BindList(cpage, ((DataTable)Session["DT"]));
            //Binds the DataList with new Values
        }
        catch (Exception)
        {
            Response.Write("Please enter an integer in the text box");
            BindList(((ControlPaging)Session["CPAGE"]), 
                     ((DataTable)Session["DT"]));
        }
        finally
        {
            cpage = null;
        }
    }

    protected void lnkNext_Click(object sender, EventArgs e)
    {
        //Increments the PageIndex by 1 (Move to Next Page)
        ((ControlPaging)Session["cpage"]).CurrentPageIndex += 1;      
        //Binds the DataList with new PageIndex            
        BindList(((ControlPaging)Session["cpage"]),
                 ((DataTable)Session["DT"]));   
    }

    protected void lnkPrev_Click(object sender, EventArgs e)
    {
        //Decrements the PageIndex by 1 (Move to Previous Page)
        ((ControlPaging)Session["cpage"]).CurrentPageIndex -= 1;                    
        //Binds the DataList with new PageIndex
        BindList(((ControlPaging)Session["cpage"]), 
                 ((DataTable)Session["DT"]));    
    }
}

ControlPaging class (Utility.dll)

The ControlPaging class has the following properties:

assembly_snap.JPG

The ControlPaging class uses PagedDataSource to implement paging. PagedDatasource has been wrapped around the ControlPaging class to ease the paging process, so the user just need to call the properties to use the class.

C#
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.UI.WebControls;
using System.Data;

namespace SyedFasih
{
    /// <summary>
    /// Provides Paging for various controls like  Repeater, Datalist etc...
    /// Author : Syed Fasih-ud-Din
    /// </summary>
    public class ControlPaging
    {
        PagedDataSource oPage;
        static int _CurrentPageIndex = 0;
        static int _PageSize = 10;  //Default
        DataTable dt;

        public ControlPaging()
        {
            oPage = new PagedDataSource();
        }

        /// <summary>
        /// Author : Syed Fasih-ud-Din
        /// Gets or Sets the PageIndex of a Control
        /// </summary>
        public int CurrentPageIndex
        {
            get
            {
                return _CurrentPageIndex;
            }
            set
            {
                _CurrentPageIndex = value;
            }
        }

        /// <summary>
        /// Author : Syed Fasih-ud-Din
        /// Gets or Sets the Page Size (Number of records per page) of a Control
        /// </summary>
        public int PageSize
        {
            get
            {
                return _PageSize;
            }
            set
            {
                _PageSize = value;
            }
        }

        /// <summary>
        /// Author : Syed Fasih-ud-Din
        /// Gets or Sets the DataSource of a Control
        /// </summary>
        public DataTable DataSource
        {
            set
            {
                dt = new DataTable();
                dt = value;
            }
            get
            {
                return dt;
            }
        }

        /// <summary>
        /// Author : Syed Fasih-ud-Din
        /// Returns the corresponding true/false  if user is at the last page
        /// </summary>
        public bool IsLastPage
        {
            get
            {
                return oPage.IsLastPage;
            }
        }

        /// <summary>
        /// Author : Syed Fasih-ud-Din
        /// Returns the corresponding true/false  if user is at the first page
        /// </summary>
        public bool IsFirstPage
        {
            get
            {
                return oPage.IsFirstPage;
            }
        }

        /// <summary>
        /// Author : Syed Fasih-ud-Din
        /// Gets the Number of Pages available w.r.t Number of records in a control
        /// </summary>
        public int PageCount
        {
            get
            {
                return oPage.PageCount;
            }
        }

        /// <summary>
        /// Author : Syed Fasih-ud-Din
        /// Implements the PAging of a Control
        /// </summary>
        public PagedDataSource DoPaging
        {
            get
            {
                oPage.AllowPaging = true;
                oPage.PageSize = PageSize;
                oPage.CurrentPageIndex = CurrentPageIndex;
                oPage.DataSource = DataSource.DefaultView;

                return oPage;
            }
        }
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) MasterKey Computer Systems
Pakistan Pakistan
My name is Syed Fasih-ud-Din
I live in Karachi, Pakistan.
Feel free to contact me
at syedfasih@gmail.com.

Programming is my profession. I like to share my knowledge with others whatever be its standard..
Currently I am working with a very good organization: MasterKey Computer Systems.

Wish Happy Programming To All..
Thank you,

Comments and Discussions

 
Generalnice job!! Pin
zubair0117-May-10 9:59
zubair0117-May-10 9:59 
Questionhow to use paging in datalist using asp.net Pin
sam_sun8321-Aug-09 1:13
sam_sun8321-Aug-09 1:13 
AnswerRe: how to use paging in datalist using asp.net Pin
Rajendra Malav2-Sep-09 1:39
Rajendra Malav2-Sep-09 1:39 
AnswerRe: how to use paging in datalist using asp.net Pin
Syed Fasih7-Oct-09 23:23
Syed Fasih7-Oct-09 23:23 
GeneralBest solution Pin
msheikh20094-May-09 20:56
msheikh20094-May-09 20:56 
GeneralNice tutorial~ Pin
aet590530-Jul-08 17:47
aet590530-Jul-08 17:47 
GeneralNice on!!!!!!!!!!!!!!!! Pin
Aqeel Ahmed Bhatti24-Apr-08 22:23
Aqeel Ahmed Bhatti24-Apr-08 22:23 
GeneralRe: Nice on!!!!!!!!!!!!!!!! Pin
Syed Fasih25-Apr-08 5:04
Syed Fasih25-Apr-08 5:04 
GeneralRe: Nice on!!!!!!!!!!!!!!!! Pin
Ramlal Panwar23-Feb-09 23:51
Ramlal Panwar23-Feb-09 23:51 
GeneralRe: Nice on!!!!!!!!!!!!!!!! Pin
Syed Fasih24-Feb-09 16:16
Syed Fasih24-Feb-09 16:16 
GeneralRe: Nice on!!!!!!!!!!!!!!!! Pin
kh200426-Mar-09 20:49
kh200426-Mar-09 20:49 
GeneralRe: Nice on!!!!!!!!!!!!!!!! Pin
kh200426-Mar-09 21:09
kh200426-Mar-09 21:09 
GeneralTo My Good Friend (Fasih) Pin
Rashid Kamal23-Apr-08 22:33
Rashid Kamal23-Apr-08 22:33 
General@fasih Pin
Hazrat Ali23-Apr-08 3:38
Hazrat Ali23-Apr-08 3:38 

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.