5,135,153 members and growing! (12,718 online)
Email Password   helpLost your password?
Web Development » Custom Controls » General     Intermediate

Pager Control for ASP.NET

By bidel.akbari

A really simple to deploy ASP.NET Pager control.
C#, VB, Windows, .NET 1.1, .NET, ADO.NET, ASP.NET, VS, VS.NET2003, Dev

Posted: 24 Aug 2005
Updated: 13 Nov 2006
Views: 76,467
Announcements



Search    
Advanced Search
Sitemap
36 votes for this Article.
Popularity: 6.49 Rating: 4.17 out of 5
4 votes, 11.1%
1
1 vote, 2.8%
2
1 vote, 2.8%
3
5 votes, 13.9%
4
25 votes, 69.4%
5

Figure 1 - Paging again!

Introduction

Paging is an important thing that every web developer should know about. In ASP.NET 1.1 and 2.0, just DataGrid and GridView has built-in support for paging, and for somebody who prefers Repeater or DataList to DataGrid or GridView (like me!), it is so painful to implement paging. And as a developer, it was very painful for me. So I decided to write a pager control to simplify this problem on my web applications in a developer friendly way. First, I implemented a version of the Pager control last year. It came with some cool features, but also had two major weaknesses.

  1. It wasn't suitable for more than 20 pages.
  2. It used querystring to get the current pPage index, and it was annoying somehow.

and hopefully the presented version has fixed both of the above issues.

  1. It has the ability to handle large size pages with something I called Smart Shortcuts, they are really cool and are shown in figure-1 in gray background cells.
  2. The generated hyperlinks do more than a simple hyperlink. they cause a postback to the server, so no more query string parameter will be needed.

If you'd used the previous version of the Pager control, some part of this article may be boring for you, but bear with me and just skip the repeated contents.

Note: the prepared samples are categorized by ASP.NET versions, just download the desired version and you will have the samples (VB and C#) and the source code together.

What a paging system needs and what it is supposed to provide

Things that we should provide our paging system:

  1. How many items I want to display per page (I call it "PageSize").
  2. Which page am I in (I call it "CurrentPage").

Things that the paging system is supposed to provide:

  1. Sort of hyperlink numbers for users to navigate through the pages (see Figure 1).
  2. Items (results) which I want to show at the current page (like a DataSet or DataTable that is bindable).
  3. Number of total records (it is required for the Pager control to render itself appropriately).

What parts does it consist of?

This paging system consists of the following parts and I will try to explain them:

The first part:

A stored procedure which lives in the database. It takes the two main parameters ("PageSize" and "CurrentPage") and return the results for the page that we are in.

The second part:

The Pager control which builds the numerical hyperlinks for us in a user friendly way. These hyperlinks will be used to navigate through the pages.

The last but not the least:

And finally, a web page which hosts the Pager control and calls the stored procedure to fetch the current page's data.

How to deploy and use them

I've provided source code and samples for ASP.NET 1.1(VB and C#) and ASP.NET 2.0 (VB and C#), so if you are interested to see some real code, just download the files. Otherwise if you want to continue, let's prepare our pager control to be deployed.

1. Write your own business specific stored procedure

1-1: Paging on SQL Server 2000:

OK, we are at the sweetest section, deployment! Let me start from the stored procedure. It comes with the demo project that you may have downloaded. Here is its screenshot that I have taken:

(You may change the procedure name, but don't forget to change the procedure name in the web application code.)

As you know, a stored procedure is a business specific object, and its variable names are strongly dependent on the names of your business objects. So, you ought to customize some of its variables. To make the world easy for myself and of course for you, I colorized the sections so that we have a special focus on them.

To modify the stored procedure to fit into your business, do the things below. We will start from the bottom to top:

  1. The blue section (except the "RowID" statement) means the output columns that you want to show on the web page. So first of all, write your own table's columns here right after the "RowID" statement. For example, assume that you want to show the "Title", "Price", and "PubDate" columns of the "Pubs" database. The blue section will change to:
    "SELECT RowID, Title, Price, PubDate"
  2. The green section means your "Select Logic". According to our example, if you have no "WHERE" statement in your query, the green section will change to:
    "SELECT Title, Price, PubDate FROM Titles"

    and if you have to use the "WHERE" statement for example, it will change to this:

    "SELECT Title, Price, PubDate FROM Titles WHERE Price > 11"

    You may use other T-SQL statements to sort the rows. As you can see, in the green section, I used an "ORDER BY" statement to sort my results. It is optional and up to you. In our example, we may want to sort our results by "Title", so we modify it to:

    "SELECT Title, Price, PubDate FROM Titles WHERE Price > 11 ORDER BY Title"
  3. OK, the pink section is part of a procedure that creates a temporary table, add your blue section's (except "RowID") columns to it. In our example, the pink part would change to:
    "Title varchar(80), Price money, PubDate datetime"
  4. And the last part is the yellow section. This section really relies on part 2 (the green guy!), so it will change the "FROM" and "WHERE" statements that you used in part 2 (green section). In our example if we don't use "WHERE" in the green part, the yellow section will become:
    "FROM Pubs"

    And if we use "WHERE" in the green part, it will become:

    "FROM Pubs WHERE Price > 11"

1-2: Paging on SQL Server 2005:

SQL Server 2005 supports paging internally via the ROW_NUMBER() function. So please take a look at the figure below:

Since this function has a great documentation on the Internet, I would not cover it here.

Congratulations! You did the hardest part of the deployment. Save the stored procedure in your desired database, and carry on.

2. Use the Pager Control

After creating the stored procedure, we will continue with the Pager control (the main excuse of the whole of this article!). Let's see how we can use it and how it can do its tasks in our paging system. I divided its useful properties into two main categories:

<<GlobalizationSettings>>

As the name shows, the language of the Pager control can be changed by these properties. Let's take a look at the screenshot below:

As you see, the default language is (en-us) but if you want, you can easily change this property to change the Pager control's language to your local language, even Unicode languages like Persian or Arabic. Also, there is a property, named RTL, which change the direction of the Pager control.

<<BehavoiuralSettings>>

You can change the behaviour of your Pager control here. See the figure below please:

  • PageSize: it is the property which sets the count of items that every page should display. [ Default value: 15 ]
  • AlternativeTextEnabled: it is a boolean property and tells the Pager control whether to generate ALT (Tooltip) text for the pager control or not. [ Default value: True ]
  • ShowFirstLast: it is a boolean property and tells the Pager control whether to show the "First" and "Last" hyperlinks or not. [ Default value: False ]
  • CompactedPageCount: it will set the count of items to render in compacted mode. If the user requests any page number greater than this value, the pager control will render itself in NotCompactedPageCounts count. For example, if you set CompactedPageCount=10 and NotCompactedPageCounts=20, if you are in a page lower than 10, the count of page hyperlinks will be 10; once you hit the tenth page, the pager will increase its number of items to 20.  [ Default value: 10 ]
  • NotCompactedPageCounts: see the CompactedPageCount description. [ Default value: 15 ]
  • EnableSmartShortCuts: a boolean property to switch smart shortcuts on/off. [ Default value: True ]
  • MaxSmartShortCutCounts: set the maximum count of smart shortcuts. [ Default value: 6 ]
  • SmartShortCutRatio: it will be used internally to generate smart shortcuts. [ Default value: 3 ]
  • SmartShortCutThreshold: if total page count is greater than this value, smart shortcuts will be generated. otherwise no smart shorcut will be generated. [ Default value: 30 ]

3. The Hoster Web Page

OK, if everything is alright till now, let's continue and complete our paging system. As you can see in the demo project, we have a web page which hosts our controls (Repeater for repeating the results and the Pager control). Let's see what happens if a user requests that page:

    protected void Page_Load(object sender, EventArgs e) {
        if (!IsPostBack) {
            pager1.CurrentIndex = 1;
            BindRepeater(1);
        }
    }        

As you can see, after getting the current page index after postback (we know it as "CurrentPage"), we will pass is to our BindRepeater method. Then it calls the procedure via a SqlCommand object and fetches the results for that page.

    public void pager_Command(object sender, CommandEventArgs e) {
        int currnetPageIndx = Convert.ToInt32(e.CommandArgument);
        pager1.CurrentIndex = currnetPageIndx;
        BindRepeater(currnetPageIndx);
    }        

and finally bind the data consumer like this:

    private void BindRepeater(int pageNo) {

        SqlConnection cn = new SqlConnection(strConn);

        SqlCommand Cmd = new SqlCommand("dbo.GetPagedProducts_sql2k5", cn);
        Cmd.CommandType = CommandType.StoredProcedure;
        SqlDataReader dr;

        Cmd.Parameters.Add("@PageSize", 
            SqlDbType.Int, 4).Value = pager1.PageSize;
        Cmd.Parameters.Add("@CurrentPage", 
            SqlDbType.Int, 4).Value = pageNo;
        Cmd.Parameters.Add("@ItemCount", 
            SqlDbType.Int).Direction = ParameterDirection.Output;

        cn.Open();
        dr = Cmd.ExecuteReader();

        Repeater1.DataSource = dr;
        Repeater1.DataBind();

        dr.Close();
        cn.Close();

        Int32 _totalRecords = Convert.ToInt32(
               Cmd.Parameters["@ItemCount"].Value);
        pager1.ItemCount = _totalRecords;
    }

Colorizing the Pager control, according to your website's colors

I hope everything is okay until now. If you are done with the deployment, let's go to customize the Pager control colors. I've created two CSS stylesheets that can colorize the Pager control in two different ways.

Take a look at these screenshots please:

LightStyle.css: Provides the above style for your Pager control (recommended for light background web pages).

DarkStyle.css: Provides the above style for your Pager control (recommended for dark background web pages).

(To customize the control in your preferred way, you should manipulate the stylesheet classes in the "Styles" folder).

A little bit more about Pager control

ASP.NET controls can be created by inheriting them from the System.Web.UI.WebControl class. And after that, just override the Render operation to build your control in the way that you want. And the Pager control is built upon this theory too.

As you will see in the source, we force the HtmlTextWriter to write our desired HTML output. Take a look at the Pager control source project to get any more details.

History

  • Nov 2006: second release. No more annoying querystring requirement, and with something cool I call SmartShortCuts to handle large amounts of pages. Nothing new, but useful (still looking forward to reading your useful feedbacks).
  • Aug 2005: first release. With some cool features, and of course, a big weakness: unable to handle large page size situations. Thanks for the great feedbacks.

That's it, I hope this little explanation could help you deploy the Pager control appropriately. Tell me what you think about this control. Any comment would be appreciated.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

bidel.akbari



Occupation: Web Developer
Location: Iran, Islamic Republic Of Iran, Islamic Republic Of

Other popular Custom Controls articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 25 of 38 (Total in Forum: 38) (Refresh)FirstPrevNext
Subject  Author Date 
QuestionI would like to increase the storage process for field, or on the basis of a sort field, how do I ?membernestcn0:43 30 Apr '08  
Generalusing with ajaxmemberstefan-t22:38 7 Dec '07  
GeneralYou can be more generic in your query...memberElfman_NE12:16 21 Nov '07  
GeneralDoesn't preserve state on postback.membertomgreen989:29 16 Nov '07  
GeneralIncorrect syntax near the keyword 'with'memberjoelu22:09 3 Oct '07  
GeneralRe: Incorrect syntax near the keyword 'with'memberalhambra-eidos4:13 17 Oct '07  
GeneralRe: Incorrect syntax near the keyword 'with'memberdieguitojr16:54 5 Nov '07  
GeneralRe: Incorrect syntax near the keyword 'with' [modified]membernestcn21:47 21 Apr '08  
GeneralTop ControlmemberTimHustler6:19 6 Aug '07  
GeneralModified versionmembersree321:21 3 Jun '07  
GeneralModified versionmembersree319:37 3 Jun '07  
GeneralThank you very much [modified]memberWangXinshu20:59 18 Apr '07  
GeneralAwesome piece of codememberjavs4:26 26 Mar '07  
GeneralSearch Engine Friendlymemberjalchr2:04 10 Feb '07  
AnswerRe: Search Engine Friendly [modified]memberbidel.akbari3:48 10 Feb '07  
GeneralRe: Search Engine FriendlymemberEnsonix Ryan14:11 14 Mar '08  
QuestionCould not load file or assembly 'ASPnetPagerV2netfx2_0' or one of its dependencies. The system cannot find the file specified.membergimblu6:32 6 Feb '07  
AnswerRe: Could not load file or assembly 'ASPnetPagerV2netfx2_0' or one of its dependencies. The system cannot find the file specified.membergimblu7:18 6 Feb '07  
GeneralQuerystring versionmembercarlbackbone5:19 22 Jan '07  
GeneralSearch Querymembermeteorbites0:45 9 Jan '07  
GeneralPaging SQL Server 2000memberJavier P. de Jorge8:55 15 Nov '06  
GeneralLimiting the Page Count Numbersmembersayedwasim0:31 16 Aug '06  
Generalimprovent again [modified]memberenjoywithme17:57 16 Jul '06  
GeneralRe: improvent againmembertianyangmao22:43 27 Oct '06  
GeneralRe: improvent againmemberikononenko6:05 1 Nov '06  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 13 Nov 2006
Editor: Smitha Vijayan
Copyright 2005 by bidel.akbari
Everything else Copyright © CodeProject, 1999-2008
Web12 | Advertise on the Code Project