Home > Articles > Programming > ASP .NET

ASP.NET Data Web Controls: Providing DataGrid Pagination

Learn how to provide pagination support for the DataGrid Web control using the default paging mechanism. You will also discover the advantages of custom paging that allows the DataSource to contain only those records that will be displayed on the current page of data the user is viewing.
This chapter is from the book

For more information on .NET, visit our .NET Reference Guide or sign up for our .NET Newsletter.

In This Chapter

  • Adding Paging Support to the DataGrid

  • Providing a More Elegant Paging Interface

  • Paging Through the DataGrid Using Custom Paging

  • Paging Through a Cached DataSet

  • On the Web

The examples we've looked at throughout the past seven chapters have displayed small amounts of data, usually around 25 database records. These examples displayed all of the data at one time. Although such an approach is sensible when dealing with manageable amounts of data, imagine if we displayed 500 database records all on one page. There would simply be too much data for the user to digest.

When presenting large amounts of data, many Web sites break the data up into pages. For example, doing a search for "DataGrid" on Google.com returns an estimated 114,000 results. Of course, I am not shown all 114,000 results at once, just 10 at a time. At the bottom of the page is a list of page numbers, allowing me to advance to the next page, or to one of the next 10 pages.

Google, obviously, is not the only Web site that breaks up large amounts of data into readable pages. All search engines do this, whether the search engine searches the entire World Wide Web or only a particular Web site. For example, searching for products by a keyword on Amazon.com will display all matching products 10 at a time.

In Chapter 7, "Sorting the DataGrid's Data," we looked at the DataGrid's built-in properties to aid with sorting. These included the AllowSorting property and the SortCommand event. As we'll see in this chapter, the DataGrid also provides a number of properties and events to assist with paging.

Adding Paging Support to the DataGrid

As we saw in Chapter 7, the first step to add sorting support to the DataGrid is to set the AllowSorting property to True. Not surprisingly, the DataGrid contains a similar property to enable paging: AllowPaging. As with sorting, this property needs to be explicitly set to True to enable the DataGrid's paging features.

Along with the AllowPaging property, there is a PageSize property that specifies how many records to display per page. This property has a default value of 10. By just setting the AllowPaging property to True and (optionally) setting the PageSize property, the DataGrid displays only the first PageSize number of rows from the DataSource. Additionally, beneath the displayed rows is a row that has < and > characters, which are rendered as hyperlinks. The previous page can be reached by clicking the < link, and the next page can be reached by clicking the > link. Figure 8.1 contains a screenshot of a DataGrid with its AllowPaging property set to True and its PageSize property set to 5 (see line 47 in Listing 8.1).


As Figure 8.1 shows, when the page is first loaded, the < character is simply a text character, not a hyperlink. This is because when the page is first loaded, we are displaying the first page of data. Therefore, there is no way the user can view the previous page.

Figure 8.1Figure 8.1. Setting AllowPaging to True displays only the PageSize records per page.

Listing 8.1 contains the source code used for the ASP.NET Web page shown in Figure 8.1. The code is similar to previous examples we've looked at throughout this book.

Listing 8.1 The DataGrid's AllowPaging and PageSize Properties Are Set

 1: <%@ import Namespace="System.Data" %>
 2: <%@ import Namespace="System.Data.SqlClient" %>
 3: <script runat="server" language="VB">
 4:   Sub Page_Load(sender as Object, e as EventArgs)
 5:    If Not Page.IsPostBack then
 6:     BindData()
 7:    End If
 8:   End Sub
11:   Sub BindData()
12:    '1. Create a connection
13:    Const strConnString as String = "server=localhost;uid=sa;pwd=;
14:    Dim objConn as New SqlConnection(strConnString)
16:    '2. Create a command object for the query
17:    Dim strSQL as String
18:    strSQL = "SELECT title, price, pubdate " & _
19:        "FROM titles "
21:    Dim objCmd as New SqlCommand(strSQL, objConn)
23:    '3. Create a DataAdapter and Fill the DataSet
24:    Dim objDA as New SqlDataAdapter()
25:    objDA.SelectCommand = objCmd
27:    objConn.Open()
29:    Dim objDS as DataSet = New DataSet()
30:    objDA.Fill(objDS, "titles")
32:    objConn.Close()
34:    'Finally, specify the DataSource and call DataBind()
35:    dgTitles.DataSource = objDS
36:    dgTitles.DataBind()
38:    objConn.Close()  'Close the connection
39:   End Sub
40: </script>
42: <form runat="server">
43:  <asp:DataGrid runat="server" id="dgTitles"
44:    Font-Name="Verdana" Font-Size="9pt" CellPadding="5"
45:    AlternatingItemStyle-BackColor="#dddddd"
46:    AutoGenerateColumns="True"
47:    AllowPaging="True" PageSize="5">
49:   <HeaderStyle BackColor="Navy" ForeColor="White" Font-Size="13pt"
50:        Font-Bold="True" HorizontalAlign="Center" />
51:  </asp:DataGrid>
52: </form>

On line 47, you can see that the DataGrid's AllowPaging property has been set to True, and its PageSize property has been set to 5.

One important difference to note between many of our previous examples and Listing 8.1 is that instead of populating our SQL query in a SqlDataReader, we are using a DataSet (lines 29 through 35). The reason we are using a DataSet is because when using the default paging, the DataSource must be set to an object that implements the ICollection interface. The DataSet implements this interface, but the DataReader classes (SqlDataReader, OleDbDataReader, and so on) do not. The default DataGrid paging requires that its DataSource implement ICollection because the DataGrid needs to be able to calculate the total number of records to determine how many total pages there are for the given DataSource. Unfortunately, the only way to determine how many total records are in a DataReader class is to iterate completely through the DataReader's rows, incrementing some counter variable, after which you cannot return to previous records.


Although the DataGrid's default paging requires that the DataSource implement the ICollection interface, the DataGrid also offers custom paging. When using custom paging, the DataSource need not implement ICollection. We will examine custom paging later in this chapter.

Allowing the User to Page Through the Data

Unfortunately, getting the DataGrid to page the data is a bit more complicated than simply setting the AllowPaging and PageSize properties. In fact, the DataGrid displayed in Figure 8.1 doesn't perform any sort of paging. If you click the > hyperlink to advance to the next page, nothing happens. That is, the ASP.NET Web page is posted back, but the exact same data is displayed again.

The good news is that only a few lines of code are needed to provide full paging support. Before we examine the code, though, let's take a brief moment to discuss how the DataGrid knows what page of data is currently being displayed, along with what happens when one of the < or > hyperlinks is clicked.

Determining the Number of Pages and the Current Page

The DataGrid has two properties that can be used to determine what page of data is currently being displayed and how many pages of data there are.

The CurrentPageIndex property is an integer value that indicates what page is currently being displayed. This index is zero-based, meaning that when the first page of data is being displayed, CurrentPageIndex equals zero. More generally, when the nth page of data is being displayed, CurrentPageIndex equals n – 1.

The PageCount property indicates how many total pages there are; the value of PageCount is equal to the number of records in the DataSource divided by the number of records you are showing per page (the value of the PageSize property). If there is any remainder left over, the PageCount value is incremented to the nearest integer. That is, if the DataSource has nine records and the PageSize property is set to 5, PageCount will equal 2, because 9 divided by 5 is 1.8; because there is a remainder, the answer is incremented to 2. There would be two pages: The first would display records 1, 2, 3, 4, and 5, and the second would display records 6, 7, 8, and 9.


In mathematical terms, the PageCount is the ceiling of the number of records in the DataSource divided by PageSize.

Because the CurrentPageIndex property specifies what page of data is being displayed in the DataGrid, CurrentPageIndex should always be between 0 and PageCount – 1.

When one of the paging hyperlinks is clicked, the ASP.NET Web page performs a postback. (Remember that your DataGrid must be placed within a Web form, as in Listing 8.1, line 42.) When the page posts back, the DataGrid's PageIndexChanged event is raised.

Our task will be to provide an event handler and wire it up to the PageIndexChanged event. All that this event handler will have to do is update the DataGrid's CurrentPageIndex property and rebind the DataSource to the DataGrid.


It is vitally important that you remember to rebind the DataGrid in the PageIndexChanged event handler. If you fail to do this, when attempting to navigate to a different page, you will still be shown the first page of data. This happens because when moving to a different page of data, the ASP.NET page is posted back, the PageIndexChanged event fires, and the PageIndexChanged event handler executes. If this event handler does not rebind the DataGrid data, the DataGrid will be rendered using the ViewState, which will redisplay the DataGrid's first page output. Therefore, as you can in line 9 in Listing 8.2, the last line of the PageIndexChanged event handler is a call to the BindData() subroutine.

The PageIndexChanged event handler must have the following definition:

Sub EventHandler(sender as Object, e as DataGridPageChangedEventHandler)

The DataGridPageChangedEventHandler class contains a NewPageIndex property that specifies what page the user wants to view. If the user clicks the < hyperlink, the value of the DataGridPageChangedEventHandler's parameter NewPageIndex property will be the value of the CurrentPageIndex property minus 1. If the user clicks the > hyperlink, the value of the DataGridPageChangedEventHandler's parameter NewPageIndex property will be the value of the CurrentPageIndex property plus 1.

As mentioned previously, all we need to do in the event handler is update the DataGrid's CurrentPageIndex property and rebind the DataSource to the DataGrid. This simply involves setting the DataGrid's CurrentPageIndex to the NewPageIndex property of the DataGridPageChangedEventHandler parameter and then calling the BindData() subroutine. The complete code for the PageIndexChanged event handler can be seen here:

Sub dgTitles_Paging(sender As Object, e As DataGridPageChangedEventArgs)
  dgTitles.CurrentPageIndex = e.NewPageIndex
End Sub

All that remains is to wire up the dgTitles_Paging event handler to the DataGrid's PageIndexChanged event. This can be done through the DataGrid's declaration. Listing 8.2 illustrates how to accomplish this.

Listing 8.2 Add an Event Handler for the DataGrid's PageIndexChanged Event

 1: <%@ import Namespace="System.Data" %>
 2: <%@ import Namespace="System.Data.SqlClient" %>
 3: <script runat="server" language="VB">
 4:  ' ... The Page_Load event handler and BindData() subroutine
 5:  '  have been omitted for brevity. Refer back to Listing 8.1 ...
 7:   Sub dgTitles_Paging(sender As Object, e As DataGridPageChangedEventArgs)
 8:    dgTitles.CurrentPageIndex = e.NewPageIndex
 9:    BindData()
10:   End Sub
11: </script>
13: <form runat="server">
14:  <asp:DataGrid runat="server" id="dgTitles"
15:    Font-Name="Verdana" Font-Size="9pt" CellPadding="5"
16:    AlternatingItemStyle-BackColor="#dddddd"
17:    AutoGenerateColumns="True"
18:    PageSize="5" AllowPaging="True"
19:    OnPageIndexChanged="dgTitles_Paging">
21:   <HeaderStyle BackColor="Navy" ForeColor="White" Font-Size="13pt"
22:        Font-Bold="True" HorizontalAlign="Center" />
23:  </asp:DataGrid>
24: </form>

Listing 8.2 contains the dgTitles_Paging event handler we looked at previously (lines 7 through 10). It also wires up the dgTitles_Paging event handler to the DataGrid's PageIndexChanged event (line 19). As with Listing 8.1, the AllowPaging and PageSize properties are set to True and 5, respectively (line 18).

With this added event handler, the ASP.NET page in Listing 8.2 pages through the data one page at a time as the user clicks the < and > hyperlinks. You can refer back to Listing 8.1 to see a screenshot of the ASP.NET Web page when you first visit it. Figure 8.2 contains a screenshot of the page after the > hyperlink has been clicked once. Note that the records displayed in Figure 8.2 are different than those in Figure 8.1. Specifically, they are records 6–10 from the titles database table.

Figure 8.2Figure 8.2. When the user clicks the > hyperlink, the second page of data is shown.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020