SIGN UP MEMBER LOGIN:    
ARTICLE

DataList Custom Paging in ASP.NET using C#

Posted by Rizwan Javed Articles | ASP.NET & Web Forms January 11, 2009
This article describes DataList Paging with Next, previous and First, Last page access functionality. A numbers list is also displayed for acessing pages faster.
Reader Level:
Download Files:
 

Introduction

This article describes DataList Paging with Next, previous and First, Last page access functionality. A numbers list is also displayed for accessing pages faster.

datatlist_paging.JPG

Background

Few days back when I required to implement custom paging in DataList(like a google paging). I search out the Internet but did not find any perfect code. Then after some effort I wrote my own code. I decided to share it with other users. Surely this will help other developers.

Using the code

Here we will discuss complete example code.

HTML in Default.aspx contains two DataList's

1) dListItems (Main DataList showing actual contents to implement paging)

2) dlPaging (used for displaying page numbers as navigation links).

Four LinkButton's to move next, previous, first and last page

A Label to display current page number out of total number of pages.

Now we come to .cs code. There are three get, set properties

1-CurrentPage (To keep current page index)

2-fistIndex & 3-lastIndex (These two properties are used to for paging DataList)

    private int CurrentPage
    {
        get
        {
            object objPage = ViewState["_CurrentPage"];
            int _CurrentPage = 0;
            if (objPage == null)
            {
                _CurrentPage = 0;
            }
            else
            {
                _CurrentPage = (int)objPage;
            }
            return _CurrentPage;
        }
        set { ViewState["_CurrentPage"] = value; }
    }
    private int fistIndex
    {
        get
        {
 
            int _FirstIndex = 0;
            if (ViewState["_FirstIndex"] == null)
            {
                _FirstIndex = 0;
            }
            else
            {
                _FirstIndex = Convert.ToInt32(ViewState["_FirstIndex"]);
            }
            return _FirstIndex;
        }
        set { ViewState["_FirstIndex"] = value; }
    }
    private int lastIndex
    {
        get
        {
 
            int _LastIndex = 0;
            if (ViewState["_LastIndex"] == null)
            {
                _LastIndex = 0;
            }
            else
            {
                _LastIndex = Convert.ToInt32(ViewState["_LastIndex"]);
            }
            return _LastIndex;
        }
        set { ViewState["_LastIndex"] = value; }
    }

we need a PagedDataSource object to get and set various properties for custom paging

PagedDataSource _PageDataSource = new PagedDataSource();

GetDataTable() method simply returns a DataTable. In example code i
am not pulling data from database. i have created a custom DataTable
and added 100 Rows to DataTable using for loop.

    private DataTable GetDataTable()
    {
        DataTable dtItems = new DataTable();
 
        DataColumn dcName = new DataColumn();
        dcName.ColumnName = "title";
        dcName.DataType = System.Type.GetType("System.String");
        dtItems.Columns.Add(dcName);
 
        DataRow row;
        for (int i = 1; i <= 100; i++)
        {
            row = dtItems.NewRow();
            row["title"] = "Sample Row: I am putting here sample text for row " + i;
            dtItems.Rows.Add(row);
 
        }
        return dtItems;
 
    }

Method BindItemsList() gets DataTable by calling GetDataTable() method

Create DataSource for _PageDataSource, set PageDataSource properties and at the end binds PageDataSource to dListItems.

    private void BindItemsList()
    {
 
        DataTable dataTable = this.GetDataTable();
        _PageDataSource.DataSource = dataTable.DefaultView;
        _PageDataSource.AllowPaging = true;
        _PageDataSource.PageSize = 10;
        _PageDataSource.CurrentPageIndex = CurrentPage;
        ViewState["TotalPages"] = _PageDataSource.PageCount;
 
        this.lblPageInfo.Text = "Page " + (CurrentPage + 1) + " of " + _PageDataSource.PageCount;
        this.lbtnPrevious.Enabled = !_PageDataSource.IsFirstPage;
        this.lbtnNext.Enabled = !_PageDataSource.IsLastPage;
        this.lbtnFirst.Enabled = !_PageDataSource.IsFirstPage;
        this.lbtnLast.Enabled = !_PageDataSource.IsLastPage;
 
        this.dListItems.DataSource = _PageDataSource;
        this.dListItems.DataBind();
        this.doPaging();
    }

BindItemsList() calls doPaging() method which actually binds paging DataList.

    private void doPaging()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("PageIndex");
        dt.Columns.Add("PageText");
 
        fistIndex = CurrentPage - 5;
 
        if (CurrentPage > 5)
        {
            lastIndex = CurrentPage + 5;
        }
        else
        {
            lastIndex = 10;
        }
        if (lastIndex > Convert.ToInt32(ViewState["TotalPages"]))
        {
            lastIndex = Convert.ToInt32(ViewState["TotalPages"]);
            fistIndex = lastIndex - 10;
        }
 
        if (fistIndex < 0)
        {
            fistIndex = 0;
        }
 
        for (int i = fistIndex; i < lastIndex; i++)
        {
            DataRow dr = dt.NewRow();
            dr[0] = i;
            dr[1] = i + 1;
            dt.Rows.Add(dr);
        }
 
        this.dlPaging.DataSource = dt;
        this.dlPaging.DataBind();
    }
 
Make a to Call BindItemList Method at PageLoad()
 
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            this.BindItemsList();
        }
    }
dlPaging_ItemCommand sets CurrentPage Property and again makes a call to BindItemsList()
    protected void dlPaging_ItemCommand(object source, DataListCommandEventArgs e)
    {
        if (e.CommandName.Equals("Paging"))
        {
            CurrentPage = Convert.ToInt16(e.CommandArgument.ToString());
            this.BindItemsList();
        }
    }

dlPaging_ItemDataBound will set Enabled equals to false when binding the LinkButton which is currently clicked from paging list

    protected void dlPaging_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        LinkButton lnkbtnPage = (LinkButton)e.Item.FindControl("lnkbtnPaging");
        if (lnkbtnPage.CommandArgument.ToString() == CurrentPage.ToString())
        {
            lnkbtnPage.Enabled = false;
            lnkbtnPage.Style.Add("fone-size", "14px");
            lnkbtnPage.Font.Bold = true;
 
        }
    }

and at the end we have Event Handlers for next, previous, first & last LinkButton's

    protected void lbtnNext_Click(object sender, EventArgs e)
    {
        CurrentPage += 1;
        this.BindItemsList();
 
    }
    protected void lbtnPrevious_Click(object sender, EventArgs e)
    {
        CurrentPage -= 1;
        this.BindItemsList();
 
    }
    protected void lbtnLast_Click(object sender, EventArgs e)
    {
 
        CurrentPage = (Convert.ToInt32(ViewState["TotalPages"]) - 1);
        this.BindItemsList();
 
    }
    protected void lbtnFirst_Click(object sender, EventArgs e)
    {
 
        CurrentPage = 0;
        this.BindItemsList();
 
    }

share this article :
post comment
 

Thank you....it works fine, just of little bit modification...... appreciable work mate's.....

Posted by piyush Singh Mar 28, 2012

Thank you so much for this is ... it saved me today .. thumbs up (Y)

Posted by database database Jan 15, 2012

Hi, Very new to asp and c#. Can you give an example of the code behind and what it replaces in the current example. Many thanks

Posted by Kevin Jan 02, 2012

i have multy more 1000 recode? how paging?

Posted by huu Dec 27, 2011

I have small qustion, I am creating datalist control through programatically, (it will create more than 5+ datalist) How can we achive the Paging for this each datalist. Please help me.

Posted by karthik Nov 20, 2011
Nevron Gauge for SharePoint
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Team Foundation Server Hosting
Become a Sponsor