ASP.NET Pager Control

This control provides a simple method for adding paging functionality to your ASP.NET site. The control itself is not "attached" to any data source; instead, that is left up to you, the developer, to take care of.

When you have a repeater or other similar controls, you don’t have a paging control. For this reason I’ve created one simple but useful. This is a control and you can customize it how you want.

The control has the following properties:

  • CssClass: for each number
  • CurrentPageCssClass for the current page number
  • Separator: Specify the string that is to appear between the number links
  • FirstText: String to be used for the "first button". Default is "|<"
  • PreviousText: String to be used for the "previous button". Default is "<"
  • NextText: String to be used for the "next button". Default is ">"
  • LastText: String to be used for the "last button". Default is ">|"
  • PageSize: A handy place to store your page sizes, not used in the code
  • NumberOfPages: The number of page links to display in between the previous/next links.
  • ShowGoTo: Displays the GoTo functionality.
  • TotalPages: Required to correctly display the number links

The is one event:

  • OnChange when a user click on a number to change page

There is a method to invoke:

  • GenerateLinks(): use this to generate the links if changes are made, such as the currentPageNumber is changed (either by you, or when the OnChange event is fired)

The event arguments provided are:

  • First: A boolean indicating whether the "first link" has been clicked
  • Previous: A boolean indicating whether the "previous link" has been clicked
  • Next: A boolean indicating whether the "next link" has been clicked
  • Last: A boolean indicating whether the "last link" has been clicked
  • PageSize: The page size you set previously
  • CurrentPageNumber: The number of the current page; this auto increments/decrements when the first/last/previous/next link is clicked

Pager.ascx

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="Pager.ascx.cs" Inherits="usercontrols_Pager" %>
<asp:LinkButton ID="LinkButtonFirst" runat="server" Text="|<" OnClick="LinkButtonFirst_Click" />
<asp:LinkButton ID="LinkButtonPrevious" runat="server" Text="<" OnClick="LinkButtonPrevious_Click" />
<asp:Repeater ID="RepeaterNumbers" runat="server">
    <ItemTemplate>
        <asp:LinkButton ID="LinkButtonNumber" runat="server" Enabled="<%#!IsCurrentPage((int)Container.DataItem) %>" CssClass="<%#!IsCurrentPage((int)Container.DataItem) ? CssClass : CurrentPageCssClass %>" Text="<%#(int)Container.DataItem%>" OnClick="LinkButtonNumber_Click" />
    </ItemTemplate>
    <SeparatorTemplate>
        <%#Separator%>
    </SeparatorTemplate>
</asp:Repeater>
<asp:LinkButton ID="LinkButtonNext" runat="server" Text=">" OnClick="LinkButtonNext_Click" />
<asp:LinkButton ID="LinkButtonLast" runat="server" Text=">|" OnClick="LinkButtonLast_Click" />
<asp:TextBox ID="TextBoxGoTo" runat="server" Width="30px" /></asp:Label>
<asp:Button ID="ButtonGoTo" runat="server" Text="Go To" OnClick="ButtonGoTo_Click" />

 

Pager.ascx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class usercontrols_Pager : System.Web.UI.UserControl
{
    #region Events
    /// Fires when a  link is clicked, the text with in the object (link button) is the number
    public event EventHandler Change;
    #endregion

    #region Properties
    /// 
    /// Gets or sets total number of pages the datasource is capable of.
    /// 
    public int TotalPages
    {
        get
        {
            if (ViewState["TotalPages"] == null)
            {
                ViewState["TotalPages"] = 0;
            }

            return Convert.ToInt32(ViewState["TotalPages"]);
        }

        set
        {
            ViewState["TotalPages"] = value;
        }
    }

    /// 
    /// Gets or sets the "First" record display text
    /// 
    public string FirstText
    {
        get; set;
    }

    /// 
    /// Gets or sets the "Previous" record display text
    /// 
    public string PreviousText
    {
        get; set;
    }

    /// 
    /// Gets or sets the "Next" record display text
    /// 
    public string NextText
    {
        get; set;
    }

    /// 
    /// Gets or sets the "Last" record display text
    /// 
    public string LastText
    {
        get; set;
    }

    /// 
    /// Gets or sets the seperator display text
    /// 
    public string Separator
    {
        get;
        set;
    }

    /// 
    /// Enables/disables the "GoTo" functionality
    /// 
    public bool ShowGoTo
    {
        get;
        set;
    }

    /// 
    /// Gets or sets the number of pages to display at
    /// 
    public int NumberOfPages
    {
        get
        {
            if (ViewState["NumberOfPages"] == null)
            {
                ViewState["NumberOfPages"] = 10;
            }

            return Convert.ToInt32(ViewState["NumberOfPages"]);
        }

        set
        {
            ViewState["NumberOfPages"] = value;
        }
    }

    /// 
    /// Gets or sets the current page number
    /// 
    public int CurrentPageNumber
    {
        get
        {
            if (ViewState["CurrentPageNumber"] == null)
            {
                ViewState["CurrentPageNumber"] = 1;
            }

            return Convert.ToInt32(ViewState["CurrentPageNumber"]);
        }

        set
        {
            ViewState["CurrentPageNumber"] = value;
        }
    }

    /// 
    /// Gets or sets the page size, mainley used as a helpful reminder
    /// 
    public int PageSize
    {
        get
        {
            if (ViewState["PageSize"] == null)
            {
                ViewState["PageSize"] = 10;
            }

            return Convert.ToInt32(ViewState["PageSize"]);
        }

        set
        {
            ViewState["PageSize"] = value;
        }
    }

    /// 
    /// Gets or sets the css class for the currently selected tab
    /// 
    public string CssClass
    {
        get; set;
    }

    public string CurrentPageCssClass
    {
        get; set;
    }

    #endregion

    #region Public Methods
    ///  Generates the pagers links based upon the controls properties 
    public void GenerateLinks()
    {
        var display = new List();
        int minimum;
        int maximum;
        CalculateBoundry(this.NumberOfPages, this.TotalPages, this.CurrentPageNumber, out minimum, out maximum);
        for (int i = minimum; i <= maximum; i++)
        {
            display.Add(i);
        }

        RepeaterNumbers.DataSource = display;
        RepeaterNumbers.DataBind();

        bool dataToDisplay = this.TotalPages > 0;

        LinkButtonFirst.Visible = dataToDisplay;
        LinkButtonPrevious.Visible = dataToDisplay;
        LinkButtonNext.Visible = dataToDisplay;
        LinkButtonLast.Visible = dataToDisplay;

        if (this.TotalPages < 1 || !this.ShowGoTo)
        {
            this.ButtonGoTo.Visible = false;
            this.TextBoxGoTo.Visible = false;
        }
        else
        {
            this.ButtonGoTo.Visible = true;
            this.TextBoxGoTo.Visible = true;
        }

        this.LinkButtonFirst.Enabled = !(this.CurrentPageNumber <= 1);
        this.LinkButtonPrevious.Enabled = !(this.CurrentPageNumber <= 1);
        this.LinkButtonNext.Enabled = !(this.CurrentPageNumber >= this.TotalPages);
        this.LinkButtonLast.Enabled = !(this.CurrentPageNumber >= this.TotalPages);
        this.LabelTotPages.Text = "/" + TotalPages;
    }
    #endregion

    #region Protected Methods
    /// 
    /// Runs the initlaisation code
    /// 
    /// The object that fired this event
    /// Additional arguments passes
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            this.LinkButtonFirst.Text = this.FirstText ?? "|<";
            this.LinkButtonPrevious.Text = this.PreviousText ?? "<";
            this.LinkButtonNext.Text = this.NextText ?? ">";
            this.LinkButtonLast.Text = this.LastText ?? ">|";
        }
    }

    /// 
    /// Determins if the current page number is the same as the page number passed through
    /// 
    /// Page number to check against
    /// True if they match
    protected bool IsCurrentPage(int pageNumber)
    {
        return pageNumber == this.CurrentPageNumber;
    }

    #region buttons clicked
    /// Fires the FirstClicked event
    /// Object that fires this event
    /// Additional arguments passed
    protected void LinkButtonFirst_Click(object sender, EventArgs e)
    {
        if (this.Change != null)
        {
            this.CurrentPageNumber = 1;
            var args = new PagerEventArgs
            {
                First = true,
                Previous = false,
                Next = false,
                Last = false,
                Number = this.CurrentPageNumber,
                PageSize = this.PageSize
            };
            this.Change(this, args);
        }
    }

    /// Fires the PreviousClicked event
    /// Object that fires this event
    /// Additional arguments passed
    protected void LinkButtonPrevious_Click(object sender, EventArgs e)
    {
        if (this.Change != null)
        {
            this.CurrentPageNumber--;
            var args = new PagerEventArgs
            {
                First = false,
                Previous = true,
                Next = false,
                Last = false,
                Number = this.CurrentPageNumber,
                PageSize = this.PageSize
            };
            this.Change(this, args);
        }
    }

    /// Fires the NumbereClicked event
    /// Object that fires this event
    /// Additional arguments passed
    protected void LinkButtonNumber_Click(object sender, EventArgs e)
    {
        if (this.Change != null)
        {
            var number = Convert.ToInt32(((LinkButton)sender).Text);
            this.CurrentPageNumber = number;
            var args = new PagerEventArgs
            {
                First = false,
                Previous = false,
                Next = false,
                Last = false,
                Number = number,
                PageSize = this.PageSize
            };
            this.Change(this, args);
        }
    }

    /// Fires the NextClicked event
    /// Object that fires this event
    /// Additional arguments passed
    protected void LinkButtonNext_Click(object sender, EventArgs e)
    {
        if (this.Change != null)
        {
            this.CurrentPageNumber++;
            var args = new PagerEventArgs
            {
                First = false,
                Previous = false,
                Next = true,
                Last = false,
                Number = this.CurrentPageNumber,
                PageSize = this.PageSize
            };
            this.Change(this, args);
        }
    }

    /// Fires the LastClicked event
    /// Object that fires this event
    /// Additional arguments passed
    protected void LinkButtonLast_Click(object sender, EventArgs e)
    {
        if (this.Change != null)
        {
            this.CurrentPageNumber = this.TotalPages;
            var args = new PagerEventArgs
            {
                First = false,
                Previous = false,
                Next = false,
                Last = true,
                Number = this.CurrentPageNumber,
                PageSize = this.PageSize
            };
            this.Change(this, args);
        }
    }

    /// Fires the NumbereClicked event
    /// Object that fires this event
    /// Additional arguments passed
    protected void ButtonGoTo_Click(object sender, EventArgs e)
    {
        if (this.Change != null)
        {
            int number;
            if (int.TryParse(this.TextBoxGoTo.Text, out number))
            {
                if (number <= this.TotalPages)
                {
                    this.CurrentPageNumber = number;
                    var args = new PagerEventArgs
                    {
                        First = false,
                        Previous = false,
                        Next = false,
                        Last = false,
                        Number = number,
                        PageSize = this.PageSize
                    };
                    this.Change(this, args);
                }
            }
        }
    }
    #endregion

    #endregion

    #region Private Methods
    /// 
    /// Calculates the upper/lower boundries for the pager to use when generating the page tabs
    /// 
    /// Maximum nuber of pages along the bottom of the pager
    /// Total number of pages in the datasource
    /// Current page number
    /// Returns the lowest boundry
    /// Returns the upper boundry
    private static void CalculateBoundry(int maximumPages, int totalPages, int currentPage, out int lowerBound, out int upperBound)
    {
        if (totalPages < maximumPages)
        {
            lowerBound = 1;
            upperBound = totalPages;
        }
        else
        {
            // NOTE: Look in to saturated arithmetic
            var rightDisplay = maximumPages / 2;
            var leftDisplay = maximumPages - rightDisplay;

            lowerBound = currentPage - leftDisplay;
            var lowerOffset = 0 - lowerBound;

            upperBound = currentPage + rightDisplay + (lowerOffset > 0 ? lowerOffset : 0);
            var upperOffset = upperBound > totalPages ? upperBound - totalPages : 0;
            upperBound = (totalPages - upperBound) > 0 ? upperBound : totalPages;

            lowerBound = lowerBound > 0 ? (lowerBound + lowerBound > upperOffset ? lowerBound - upperOffset + 1 : 1) : 1;
        }
    }

    #endregion
}

/// Event agruments for pager control
public class PagerEventArgs : EventArgs
{
    /// Gets or sets the page number that is fired
    public int Number
    {
        get; set;
    }

    /// Gets or sets a value indicating whether the first button has been click
    public bool First
    {
        get; set;
    }

    /// Gets or sets a value indicating whether the previous button has been click
    public bool Previous
    {
        get; set;
    }

    /// Gets or sets a value indicating whether the next button has been click
    public bool Next
    {
        get; set;
    }

    /// Gets or sets a value indicating whether the last button has been click
    public bool Last
    {
        get; set;
    }

    /// Gets or sets the number of rows each page contains
    public int PageSize
    {
        get;
        set;
    }
}

 

CSS

/* Search page Paging */
.paging a {
    background-color: #dcdcdc;
    padding: 5px 7px;
    text-decoration: none;
    border: 1px solid #dcdcdc;
    margin-left: 3px;
}

    .paging a:hover {
        background-color: #e5e5e5;
        color: #9ea0a3;
        border: 1px solid #9ea0a3;
    }

.paging span {
    padding: 3px 5px;
    color: #000000;
    font-size: 12px;
}

.paging .next {
    margin-left: 3px;
}

.paging a.currentpage {
    background-color: #00AFBD;
    color: #ffffff;
    font-weight: bold;
}

.paging input[type=text] {
    font-size: 12px;
    padding: 3px;
    margin-left: 15px;
    margin-right: 3px;
}

.paging input[type=submit] {
    font-size: 12px;
    padding: 3px;
    margin-right: 3px;
}
Download Pager.zip (2.9KB) usercontrol

Advertsing

125X125_06

TagCloud

MonthList

CommentList