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!
Database Paging with a DataGrid Web Control
To implement paging with the DataGrid Web control, perform the following simple steps:
Set the AllowPaging property of the DataGrid Web control to True.
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">