ASP.NET paging control

Chris S picture Chris S · Mar 17, 2009 · Viewed 17k times · Source

I'm looking for a decent paging control in ASP.NET, much like the Stackoverflow pager. Can anyone recommend one?

I'd prefer one that didn't use Postback either, just a customisable querystring.

Answer

Tom picture Tom · Mar 17, 2009

It's quite easy to roll your own. I created a simple user control based on the stack overflow pager with two properties...

  1. Total number of pages available according to the underlying data
  2. Number of links to show

The selected page is determined by reading the query string. The biggest challenge was altering the URL with the new page number. This method uses a query string parameter 'p' to specify which page to display...

string getLink(int toPage)
{
    NameValueCollection query = HttpUtility.ParseQueryString(Request.Url.Query);
    query["p"] = toPage.ToString();

    string url = Request.Path;

    for(int i = 0; i < query.Count; i++)
    {
        url += string.Format("{0}{1}={2}", 
            i == 0 ? "?" : "&", 
            query.Keys[i], 
            string.Join(",", query.GetValues(i)));
    }

    return url;
}

A simple formula to determine the range of page numbers to show...

int min = Math.Min(Math.Max(0, Selected - (PageLinksToShow / 2)), Math.Max(0, PageCount - PageLinksToShow + 1));
int max = Math.Min(PageCount, min + PageLinksToShow);

Each link then gets generated using something like (where min and max specify the range of page links to create)...

for (int i = min; i <= max; i++)
{
    HyperLink btn = new HyperLink();
    btn.Text = (i + 1).ToString();
    btn.NavigateUrl = getLink(i);
    btn.CssClass = "pageNumbers" + (Selected == i ? " current" : string.Empty);
    this.Controls.Add(btn);
}

One can also create 'Previous' (and 'Next') buttons...

HyperLink previous = new HyperLink();
previous.Text = "Previous";
previous.NavigateUrl = getLink(Selected - 1);

The first and last buttons are straight forward...

HyperLink previous = new HyperLink();
previous.Text = "1";
first.NavigateUrl = getLink(0);

In determining when to show the "...", show a literal control when the link range is not next to the first or last pages...

if (min > 0)
{
    Literal spacer = new Literal();
    spacer.Text = "&hellip;";
    this.Controls.Add(spacer);
}

Do the same for above for "max < PageCount".

All of this code is put in an override method of CreateChildControls.