When you think ASP, think...
Recent Articles
All Articles
ASP.NET Articles [1.x] [2.0]
ASPFAQs.com
Message Board
Related Web Technologies
User Tips!
Coding Tips
Search

Sections:
Book Reviews
Sample Chapters
Commonly Asked Message Board Questions
Headlines from ASPWire.com
JavaScript Tutorials
MSDN Communities Hub
Official Docs
Security
Stump the SQL Guru!
Web Hosts
XML Info
Information:
Advertise
Feedback
Author an Article
Technology Jobs

















internet.com
IT
Developer
Internet News
Small Business
Personal Technology
International

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers
ASP ASP.NET ASP FAQs Message Board Feedback ASP Jobs
Print this page.

Windows Systems Administrator
Jupitermedia
US-CT-Darien

Justtechjobs.com Post A Job | Post A Resume

Published: Saturday, July 21, 2001

Paging Database Results in ASP.NET
By Scott Mitchell


  • Read Part 1

  • In Part 1 we looked at how to bind a DataSet to the DataGrid Web control. However, in our live demo we noted that the sheer number of results made the data hard to consume for visitors. Ideally, we'd like to page this data. In this part, we'll look at how to implement paging using the DataGrid Web control. It is surprisingly easy!

    - continued -

    Database Paging with a DataGrid Web Control
    To implement paging with the DataGrid Web control, perform the following simple steps:

    1. Set the AllowPaging property of the DataGrid Web control to True.
    2. Set the OnPageIndexChanged event handler of the DataGrid Web control to a Page-level event handler that contains the following definition:

      Sub EventHandlerName(sender as Object, e as DataGridPageChangedEventArgs)
         ...
      End Sub
      

    That's all there is to it! So, in order to make the DataGrid we examined in Part 1 able to page data, we must first set the needed properties and event handlers of the DataGrid Web control. The following HTML content illustrates these changes:

    <asp:datagrid id="dgPopularFAQs" runat="server" BorderWidth="0"
                  CellPadding="2" Width="100%"
                  Font-Name="Verdana"
                  Font-Size="Smaller"
                  AutoGenerateColumns="False"
    				
                  HeaderStyle-HorizontalAlign="Center"
                  HeaderStyle-Font-Bold="True"
                  HeaderStyle-BackColor="Navy"
                  HeaderStyle-ForeColor="White"
    				
                  AlternatingItemStyle-BackColor="#dddddd"
    				
                  AllowPaging="True"
                  PageSize="15"
                  OnPageIndexChanged="dgPopularFAQs_Paged">
       ...
    </asp:datagrid>		
    

    Note that I also took a moment to set the PageSize property to a value of 15. This property indicates how many records to show per page; if not specified, it defaults to a value of 10. Now all we need to do is provide the event handler for when a page index is changed, dgPopularFAQs_Paged. The code for this event handler is painfully simple: all we need to do is set the DataGrid Web control's CurrentPageIndex property to the value of the new page, which is passed in through the DataGridPageChangedEventArgs parameter of the event handler.

    <script language="vb" runat="server">
    
      ... Other functions/subs omitted for brevity ...
    
      Sub dgPopularFAQs_Paged(sender as Object , e as DataGridPageChangedEventArgs)
        dgPopularFAQs.CurrentPageIndex = e.NewPageIndex
        BindData()
      End Sub
    </script>

    Note that we need to recreate and rebind our DataSet to the DataGrid Web control after we set the DataGrid Web control's CurrentPageIndex property. Also note that we'll want to change the Page_Load event handler so that the BindData() subroutine is only called when the page is first visited. On any postbacks, the dgPopularFAQs_Paged event handler will handle recreating the DataSet and rebinding it to the DataGrid Web control. To implement this change in the Page_Load event handler, use the following code:

    <script language="vb" runat="server">
      Sub Page_Load(sender as Object, e as EventArgs)
        If Not Page.IsPostBack then
          BindData()
        End If	
      End Sub
    
      ... Other functions/subs omitted for brevity ...
    </script>

    That's all that's needed! A live demo of the paged DataGrid Web control can be seen; note that in the live demo some further enhancements are made to the DataGrid Web control in order to improve the end output. Additionally, the DataGrid employs a PagerStyle tag, which provides for a more customized output of the paging controls. The PagerStyle should appear within the DataGrid Web control's definition like so:

    <asp:datagrid ...>
       <PagerStyle Mode="<i>Mode</i>"
                NextPageText="<i>NextPageText</i>" PrevPageText="<i>PrevPageText</i>"
                Position="<i>PagePosition</i>">
       </PagerStyle> 			
    
       ...
    </asp:datagrid>
    

    The PageStyle's Mode can be set to one of two values: NextPrev or NumericPages. The Position value can have one of three values: Top, Bottom, or TopAndBottom. Be sure to try out these different values for these two settings to see the effects. (Note that the Position property defaults to Bottom.)

    Caveats
    The most important thing to realize when paging data with the DataGrid's AllowPaging property is that each time the user navigates to a new page the entire DataSet is rebuilt. While this is not a big concern for small DataSets, imagine that you are wanting to page the results of a SQL query that results in, say, 1,000 rows. Such an approach would be taxing, since the database would have to rebuild a 1,000-row DataSet each and every time the user visited any page of the data. The DataGrid Web control provides an AllowCustomPaging option that does not suffer from this limitation. To learn more about custom paging, consult the documentation.

    Also note that to utilize the default paging with a DataGrid Web control you must use a DataSet. That is, if you set AllowPaging to True but do not employ custom paging, you cannot bind a SqlDataReader or OleDbDataReader to the DataGrid Web control and implement paging. If you attempt to do so you will receive an error along the lines of: "To support paging, you must use an object that supports the ICollection interface."

    This error message occurs because the DataReader objects do not support the ICollection interface. Note that the DataSet does not support this intercace directly either; however, the DataSet does support the IListSource interface, which is inherited from the IList interface, which is inherited from the ICollection interface. Hence, the DataSet can be used to implement paging with the DataGrid Web control.

    Conclusion
    As this article has (hopefully) illustrated, paging database data with ASP.NET is painfully easy. By using the DataGrid Web control and just a few lines of code, you can simply implement a nice-looking, easy-to-use paging system. Compare this technique and output to the mountains of classic ASP script code that was required. Bleh. For more information on ASP.NET be sure to check out the ASP.NET Article Index.

    Happy Programming!

  • By By Scott Mitchell


    Attachments:

  • View the DataGrid Binding live demo
  • View the DataGrid Paging live demo


    Windows Internet Technology | ASP.NET [1.x] [2.0] | ASPMessageboard.com | ASPFAQs.com | Advertise | Feedback | Author an Article



  • JupiterOnlineMedia

    internet.comearthweb.comDevx.commediabistro.comGraphics.com

    Search:

    Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

    Jupitermedia Corporate Info


    Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

    Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

    Solutions
    Whitepapers and eBooks
    Microsoft Article: HyperV-The Killer Feature in WinServer ‘08
    Avaya Article: How to Feed Data into the Avaya Event Processor
    Microsoft Article: Install What You Need with Win Server ‘08
    HP eBook: Putting the Green into IT
    Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
    Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
    Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
    Avaya Article: Setting Up a SIP A/S Development Environment
    IBM Article: How Cool Is Your Data Center?
    Microsoft Article: Managing Virtual Machines with Microsoft System Center
    HP eBook: Storage Networking , Part 1
    Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
    MORE WHITEPAPERS, EBOOKS, AND ARTICLES
    Webcasts
    Intel Video: Are Multi-core Processors Here to Stay?
    On-Demand Webcast: Five Virtualization Trends to Watch
    HP Video: Page Cost Calculator
    Intel Video: APIs for Parallel Programming
    HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
    Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
    MORE WEBCASTS, PODCASTS, AND VIDEOS
    Downloads and eKits
    Sun Download: Solaris 8 Migration Assistant
    Sybase Download: SQL Anywhere Developer Edition
    Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
    Red Gate Download: SQL Compare Pro 6
    Iron Speed Designer Application Generator
    MORE DOWNLOADS, EKITS, AND FREE TRIALS
    Tutorials and Demos
    How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
    eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
    IBM Article: Collaborating in the High-Performance Workplace
    HP Demo: StorageWorks EVA4400
    Intel Featured Algorhythm: Intel Threading Building Blocks--The Pipeline Class
    Microsoft How-to Article: Get Going with Silverlight and Windows Live
    MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES