Limit the page numbers to show on Custom Paging

6.6k Views Asked by At

http://www.aspsnippets.com/Articles/Custom-Paging-in-ASPNet-GridView-using-SQL-Server-Stored-Procedure.aspx

Based on the tutorial above, I was able to create a custom paging on my gridview, However, I want to limit the page number to be shown on the page. Example When I have 10,000 records to display in a 10 rows per page setting, the page links will load 1 - 1000 page links which is not ideal.

How can I make the output something like this:

First 1 2 3 4 5 6 7 8 9 10 last

and adjust automatically

First 2 3 4 5 6 7 8 9 10 11 last

and so on.

Here's the code that creates the all page showing setting

private void PopulatePager(int recordCount, int currentPage)
{
    double dblPageCount = (double)((decimal)recordCount / decimal.Parse(ddlPageSize.SelectedValue));
    int pageCount = (int)Math.Ceiling(dblPageCount);
    List<ListItem> pages = new List<ListItem>();
    if (pageCount > 0)
    {
        pages.Add(new ListItem("First", "1", currentPage > 1));
        for (int i = 1; i <= pageCount; i++)
        {
            pages.Add(new ListItem(i.ToString(), i.ToString(), i != currentPage));
        }
        pages.Add(new ListItem("Last", pageCount.ToString(), currentPage < pageCount));
    }
    rptPager.DataSource = pages;
    rptPager.DataBind();
}
3

There are 3 best solutions below

4
potatopeelings On BEST ANSWER

Change you if block to this

if (pageCount > 0)
{
    int showMax = 10;
    int startPage;
    int endPage;
    if (pageCount <= showMax) 
    {
        startPage = 1;
        endPage = pageCount;
    }
    else
    {
        startPage = currentPage;
        endPage = currentPage + showMax - 1;
    }

    pages.Add(new ListItem("First", "1", currentPage > 1));

    for (int i = startPage; i <= endPage; i++)
    {
        pages.Add(new ListItem(i.ToString(), i.ToString(), i != currentPage));
    }

    pages.Add(new ListItem("Last", pageCount.ToString(), currentPage < pageCount));
}

Change showMax as necessary.

1
Pradnya Bolli On

Use this

Set Pager setting property

and more information use GridView Paging Sample in ASP.NET

0
SaLh .A.J On

You can also add this to add exact number of pages you have

      for (int i = startPage; i <= endPage && i<dblPageCount; i++)