How to use custom pagination

0

In this time CMSN Software Tutorials has decided to provide a enhancement for our previous tutorial("How to use pagination with repeater"). "How to use custom pagination" shows you the way of integrating data level pagination with the asp.net Repeater control. Here we are using hyperlinks for the pagination points instead of using LinkButtons. that means users can bookmark any page at any time.

Following sample show you how to use our custom pagination control.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CustomPagination.aspx.cs"
    Inherits="CMSN.Software.Tutorials.HowToUseCustomPagination.CustomPagination" %>
 
<%@ Register Src="UserControls/CustomizedPagination.ascx" TagName="CustomizedPagination"
    TagPrefix="uc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>How to use custom pagination</title>
    <style type="text/css">
        .selected-page
        {
            background#a5b8da;
            background-moz-linear-gradient(top, #a5b8da 0%, #7089b3 100%);
            background-webkit-gradient(linear, 0% 0%, 0% 100%, from(#a5b8da), to(#7089b3));
            border1px solid #6c84ab;
            -moz-border-radius10px;
            -webkit-border-radius10px;
            border-radius10px;
            color#fff;
            font-size11px;
            font-weightbold;
            line-height1;
            text-aligncenter;
            padding3px 5px;
            margin0 1px;
        }
        
        .pagination-point
        {
            background#fafafa;
            background-moz-linear-gradient(top, #fafafa 0%, #dfdfe2 100%);
            background-webkit-gradient(linear, 0% 0%, 0% 100%, from(#fafafa), to(#dfdfe2));
            border1px solid #929395;
            -moz-border-radius8px;
            -webkit-border-radius8px;
            border-radius8px;
            color#7d7d7d;
            font-size11px;
            font-weightbold;
            line-height1;
            text-aligncenter;
            text-decorationnone;
            padding3px 5px;
            margin0 1px;
        }
    </style>
</head>
<body>
    <form id="PaginationWithRepeaterForm" runat="server">
    <div>
        <asp:Label ID="PaginationDisplayText" runat="server"></asp:Label>
        <hr />
        <asp:Repeater runat="server" ID="PaginatingRepeater">
            <ItemTemplate>
                <%# Eval("key")%>
                |
                <%# Eval("value")%>
                <br />
            </ItemTemplate>
        </asp:Repeater>
        <uc1:CustomizedPagination ID="RepeaterCustomPagination" runat="server" />
    </div>
    </form>
</body>
</html>

First we need to register the custom pagination user control to our page. then we can add the user control to the page. If you drag & drop user control to the design view above step will automatically done by the visual studio. Then we have label to display pagination status and repeater control.

//-----------------------------------------------------------------------
// <copyright file="CustomPagination.aspx.cs" company="CMSN Software">
//    Copyright © 2011  CMSN Software
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see http://www.gnu.org/licenses.
// </copyright>
//-----------------------------------------------------------------------
 
namespace CMSN.Software.Tutorials.HowToUseCustomPagination
{
    using System;
    using System.Data;
    using System.Globalization;
 
    /// <summary>
    /// Sample page to show pagination functionality
    /// </summary>
    public partial class CustomPagination : System.Web.UI.Page
    {
        /// <summary>
        /// pagination size
        /// </summary>
        private const int PaginationSize = 10;
 
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            // set the pagination size (number of records per page).
            this.RepeaterCustomPagination.PaginationSize = PaginationSize;
 
            // set data source to the pagination control
            this.RepeaterCustomPagination.DataSource = SampleData.SampleDataList((this.RepeaterCustomPagination.CurrentPage - 1) * PaginationSize, this.RepeaterCustomPagination.CurrentPage * PaginationSize);
 
            // set the repeater control to be paged.
            this.RepeaterCustomPagination.RepeaterControl = PaginatingRepeater;
 
            // display first and last links. (default false)  
            this.RepeaterCustomPagination.ShowFirstLast = true;
 
            // selected page style.
            this.RepeaterCustomPagination.SelectedPageCssClass = "selected-page";
 
            // pagination point style
            this.RepeaterCustomPagination.PaginationPointCssClass = "pagination-point";
            this.RepeaterCustomPagination.TotalRecordCount = SampleData.TemporaryData().Count;
 
            // navigation links style
            this.RepeaterCustomPagination.NavigationCssClass = "pagination-point";
        }
 
        /// <summary>
        /// Handles the PreRender event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_PreRender(object sender, EventArgs e)
        {
            // set the pagination status label text.
            this.PaginationDisplayText.Text = "Showing " + RepeaterCustomPagination.CurrentPageText + " of " + RepeaterCustomPagination.Count;
        }
    }
}

Here we use "SampleData" class to generate dummy data. we can set all the user control properties at the Page_Load event but to get the CurrentPageText we have to access it Page_PreRender event.

Following code shows how to implement the pagination user control. The main functionality of the control done by using PagedDataSource control.
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="CustomizedPagination.ascx.cs"
    Inherits="CMSN.Software.Tutorials.HowToUseCustomPagination.CustomizedPagination" %>
<asp:Panel ID="Pagination" runat="server">
    <asp:HyperLink ID="FirstPageLink" runat="server">&lt;&lt;</asp:HyperLink> 
    <asp:HyperLink ID="PreviousPageLink" runat="server">&lt;</asp:HyperLink> 
    <asp:Panel runat="server" ID="PaginationPoints" Style="display: inline;">
    </asp:Panel>
    <asp:HyperLink ID="NextPageLink" runat="server">&gt;</asp:HyperLink> 
    <asp:HyperLink ID="LastPageLink" runat="server">&gt;&gt;</asp:HyperLink> 
</asp:Panel>
    

Here we use four HyperLink controls for the navigation controls. And pagination points will be dynamically generated based on the page count.

//-----------------------------------------------------------------------
// <copyright file="CustomizedPagination.ascx.cs" company="CMSN Software">
//    Copyright © 2011  CMSN Software
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see http://www.gnu.org/licenses.
// </copyright>
//-----------------------------------------------------------------------
 
namespace CMSN.Software.Tutorials.HowToUseCustomPagination
{
    using System;
    using System.Collections;
    using System.Collections.Specialized;
    using System.ComponentModel;
    using System.Globalization;
    using System.Web;
    using System.Web.UI.WebControls;
 
    /// <summary>
    /// Enumeration for pagination mode
    /// </summary>
    public enum PaginationType
    {
        /// <summary>
        /// range mode
        /// </summary>
        Range,
 
        /// <summary>
        /// numeric mode
        /// </summary>
        Numeric
    }
 
    /// <summary>
    /// pagination control for repeater
    /// </summary>
    public partial class CustomizedPagination : System.Web.UI.UserControl
    {
        /// <summary>
        /// configuration name of search result page url
        /// </summary>
        private const string MobileJobSearchResultPageConfigName = "MobileJobSearchResultPage";
 
        /// <summary>
        /// NameValueCollection for get or set query string
        /// </summary>
        private NameValueCollection queryString;
 
        #region Public Properties
        /// <summary>
        /// Gets or sets the pagination mode.
        /// </summary>
        /// <value>
        /// The pagination mode.
        /// </value>
        [DefaultValue(PaginationType.Range)]
        public PaginationType PaginationMode { getset; }
 
        /// <summary>
        /// Gets or sets the size of the pagination.
        /// </summary>
        /// <value>
        /// The size of the pagination.
        /// </value>
        public int PaginationSize { getset; }
 
        /// <summary>
        /// Gets or sets the repeater control.
        /// </summary>
        /// <value>
        /// The repeater control.
        /// </value>
        public Repeater RepeaterControl { getset; }
 
        /// <summary>
        /// Gets or sets the data source.
        /// </summary>
        /// <value>
        /// The data source.
        /// </value>
        public IEnumerable DataSource { getset; }
 
        /// <summary>
        /// Gets or sets the total record count.
        /// </summary>
        /// <value>
        /// The total record count.
        /// </value>
        public int TotalRecordCount { getset; }
 
        /// <summary>
        /// Gets the current page.
        /// </summary>
        public int CurrentPage
        {
            get
            {
                int pageNumber = 1;
                if (!string.IsNullOrEmpty(Request["CurrentPage"]))
                {
                    pageNumber = int.Parse(Request["CurrentPage"], CultureInfo.CurrentCulture);
                }
 
                return pageNumber;
            }
        }
 
        /// <summary>
        /// Gets the page count.
        /// </summary>
        public int PageCount
        {
            get
            {
                return ViewState["_PageCount"] == null ? 0 : int.Parse(ViewState["_PageCount"].ToString(), CultureInfo.InvariantCulture);
            }
 
            private set
            {
                ViewState["_PageCount"] = value;
            }
        }
 
        /// <summary>
        /// Gets the Results count.
        /// </summary>
        public int Count
        {
            get
            {
                return ViewState["_Count"] == null ? 0 : int.Parse(ViewState["_Count"].ToString(), CultureInfo.InvariantCulture);
            }
 
            private set
            {
                ViewState["_Count"] = value;
            }
        }
 
        /// <summary>
        /// Gets the current page text.
        /// </summary>
        public string CurrentPageText
        {
            get
            {
                return ViewState["_CurrentPageText"] == null ? "0" : ViewState["_CurrentPageText"].ToString();
            }
 
            private set
            {
                this.ViewState["_CurrentPageText"] = value;
            }
        }
 
        /// <summary>
        /// Gets or sets the pagination point CSS class.
        /// </summary>
        /// <value>
        /// The pagination point CSS class.
        /// </value>
        public string PaginationPointCssClass { getset; }
 
        /// <summary>
        /// Gets or sets the seected page CSS class.
        /// </summary>
        /// <value>
        /// The seected page CSS class.
        /// </value>
        public string SelectedPageCssClass { getset; }
 
        /// <summary>
        /// Gets or sets the CSS class.
        /// </summary>
        /// <value>
        /// CSS class for the paginatiopn control
        /// </value>
        public string CssClass { getset; }
 
        /// <summary>
        /// Gets or sets the navigation CSS class.
        /// </summary>
        /// <value>
        /// The navigation CSS class.
        /// </value>
        public string NavigationCssClass { getset; }
 
        /// <summary>
        /// Gets or sets a value indicating whether [show first last].
        /// </summary>
        /// <value>
        ///   <c>true</c> if [show first last]; otherwise, <c>false</c>.
        /// </value>
        [DefaultValue(false)]
        public bool ShowFirstLast { getset; }
 
        /// <summary>
        /// Gets or sets the first page link text.
        /// </summary>
        /// <value>
        /// The first page link text.
        /// </value>
        [DefaultValue("<<")]
        public string FirstPageLinkText { getset; }
 
        /// <summary>
        /// Gets or sets the last page link text.
        /// </summary>
        /// <value>
        /// The last page link text.
        /// </value>
        [DefaultValue(">>")]
        public string LastPageLinkText { getset; }
 
        /// <summary>
        /// Gets or sets the previous page link text.
        /// </summary>
        /// <value>
        /// The previous page link text.
        /// </value>
        [DefaultValue("<")]
        public string PreviousPageLinkText { getset; }
 
        /// <summary>
        /// Gets or sets the next page link text.
        /// </summary>
        /// <value>
        /// The next page link text.
        /// </value>
        [DefaultValue(">")]
        public string NextPageLinkText { getset; }
        #endregion
 
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            this.queryString = HttpUtility.ParseQueryString(Request.QueryString.ToString());
            this.GeneratePagination();
            this.FirstPageLink.NavigateUrl = this.GenerateNavigationLink(1);
            this.LastPageLink.NavigateUrl = this.GenerateNavigationLink(this.PageCount);
            this.PreviousPageLink.NavigateUrl = this.GenerateNavigationLink(this.CurrentPage - 1);
            this.NextPageLink.NavigateUrl = this.GenerateNavigationLink(this.CurrentPage + 1);
            if (this.ShowFirstLast)
            {
                // hide first page link on first page.
                this.PreviousPageLink.Visible = this.FirstPageLink.Visible = !(this.CurrentPage == 1);
 
                // hide last page link on last page.
                this.NextPageLink.Visible = this.LastPageLink.Visible = !(this.CurrentPage == this.PageCount);
 
                // set the first page link text
                if (!string.IsNullOrEmpty(this.FirstPageLinkText))
                {
                    this.FirstPageLink.Text = this.FirstPageLinkText;
                }
 
                // set the last page link text
                if (!string.IsNullOrEmpty(this.LastPageLinkText))
                {
                    this.LastPageLink.Text = this.LastPageLinkText;
                }
 
                if (!string.IsNullOrEmpty(this.PreviousPageLinkText))
                {
                    this.PreviousPageLink.Text = this.PreviousPageLinkText;
                }
 
                if (!string.IsNullOrEmpty(this.NextPageLinkText))
                {
                    this.NextPageLink.Text = this.NextPageLinkText;
                }
            }
            else
            {
                this.FirstPageLink.Visible = false;
                this.LastPageLink.Visible = false;
            }
 
            this.NextPageLink.CssClass = this.PreviousPageLink.CssClass = this.FirstPageLink.CssClass = this.LastPageLink.CssClass = this.NavigationCssClass;
            this.Pagination.CssClass = this.CssClass;
        }
 
        /// <summary>
        /// Creates the pagination point.
        /// </summary>
        /// <param name="title">title of the pagination point</param>
        /// <param name="index">index of the pagination point</param>
        /// <returns>Pagination point link</returns>
        private HyperLink CreatePaginationPoint(string title, int index)
        {
            HyperLink paginationPoint = new HyperLink();
            paginationPoint.ID = index.ToString(CultureInfo.InvariantCulture);
            paginationPoint.Text = title;
            paginationPoint.CssClass = this.PaginationPointCssClass;
            paginationPoint.NavigateUrl = this.GenerateNavigationLink(index + 1);
            return paginationPoint;
        }
 
        /// <summary>
        /// Generates the pagination.
        /// </summary>
        private void GeneratePagination()
        {
            PagedDataSource pagedDatasource = new PagedDataSource();
            pagedDatasource.DataSource = this.DataSource;
            pagedDatasource.AllowCustomPaging = true;
            pagedDatasource.AllowPaging = true;
            pagedDatasource.PageSize = this.PaginationSize;
            this.Count = this.TotalRecordCount;
            this.PaginationSize = (this.PaginationSize == 0) ? this.TotalRecordCount : this.PaginationSize;
            PaginationPoints.Controls.Clear();
 
            int startIndex = 0;
            if (this.TotalRecordCount % this.PaginationSize == 0)
            {
                this.PageCount = this.TotalRecordCount / this.PaginationSize;
            }
            else
            {
                this.PageCount = (this.TotalRecordCount / this.PaginationSize) + 1;
            }
 
            string paginationPointText;
            int startNumber;
            int endNumber;
            for (int i = startIndex; i < this.PageCount; i++)
            {
                startNumber = ((i + 1) * this.PaginationSize) + 1 - this.PaginationSize;
                endNumber = (i + 1) * this.PaginationSize > this.TotalRecordCount ? this.TotalRecordCount : (i + 1) * this.PaginationSize;
                if (this.PaginationMode == PaginationType.Numeric)
                {
                    paginationPointText = (i + 1).ToString(CultureInfo.InvariantCulture);
                }
                else
                {
                    paginationPointText = startNumber + " - " + endNumber;
                }
 
                if (i == this.CurrentPage - 1)
                {
                    this.CurrentPageText = paginationPointText;
                    using (Label selectedPage = new Label())
                    {
                        selectedPage.Text = paginationPointText;
                        selectedPage.CssClass = this.SelectedPageCssClass;
                        PaginationPoints.Controls.Add(selectedPage);
                    }
                }
                else if (i < this.PageCount)
                {
                    PaginationPoints.Controls.Add(this.CreatePaginationPoint(paginationPointText, i));
                }
            }
 
            this.RepeaterControl.DataSource = pagedDatasource;
            this.RepeaterControl.DataBind();
        }
 
        /// <summary>
        /// Generates the navigation link.
        /// </summary>
        /// <param name="linkIndex">Index of the link.</param>
        /// <returns>generated navigation link as a string</returns>
        private string GenerateNavigationLink(int linkIndex)
        {
            NameValueCollection linkUrl = this.queryString;
            linkUrl["CurrentPage"] = linkIndex.ToString(CultureInfo.InvariantCulture);
            string resultPage = Request.Url.GetLeftPart(UriPartial.Path);
            return resultPage + "?" + linkUrl.ToString();
        }
    }
}

This code containing the tricky part of pagination. You can understand the logic by going through the above code.

Following code containing sample methods to generate dummy data. you can replace this class by your data layer.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Globalization;
 
namespace CMSN.Software.Tutorials.HowToUseCustomPagination
{
    public sealed class SampleData
    {
        /// <summary>
        /// Prevents a default instance of the <see cref="SampleData"/> class from being created.
        /// </summary>
        private SampleData() { }
 
        public static Dictionary<stringstring> SampleDataList(int startIndex, int pageSize)
        {
            Dictionary<stringstring> sampleTable = new Dictionary<stringstring>();
            var query = from p in TemporaryData()
                        .Take(pageSize)
                        .Skip(startIndex)
                        select new
                        {
                            FirstColumn = p.Key,
                            SecondColumn = p.Value
                        };
            foreach (var row in query)
            {
                sampleTable.Add(row.FirstColumn, row.SecondColumn);
            }
            return sampleTable;
        }
 
        public static Dictionary<string,string> TemporaryData()
        {
            Dictionary<stringstring> sampleDataSet = new Dictionary<stringstring>();
            for (int i = 1; i <= 49; i++)
            {
                sampleDataSet.Add("Raw " + i + " Cell 1""Raw " + i + " Cell 2");
            }
 
            return sampleDataSet;
        }
    }
}

Above code shows how to implement data level pagination.The main actors of here are IQueryable Take and Skip methods. These methods create an statement that only returns records between the rows starting at the Take value, and then skipping all the rows in the Skip value instead of the whole data

Download tutorial

0 comments:

Post a Comment