GridView Sorting and Paging

The <asp:GridView> control provides a convenient means to display information from a data source without a lot of scripting, in some cases with no scripting at all. It also comes with internal mechanisms to sort displayed information in ascending and descending sequence by one or more columns of data; plus, it provides the option to display output as a sequence of shorter pages rather than all at once. Sorting and paging are two built-in features that otherwise would require entensive coding, again permitting the page developer to produce dynamic output through declarative, rather than scripting, methods.

Sorting a GridView

When a GridView has the property setting AutoGenerateColumns="True" (the default), provision to sort the displayed information on any generated column of data is as simple as adding the AllowSorting="True" attribute to the control. The generated column headings become clickable text to sort the information in sequence by the values in the column. Clicks on the headings alternate sorting between ascending and descending sequence. The following GridView demonstrates sorting capabilities produced when columns are automatically generated.

BookIDBookTitleBookPriceBookQtyBookSale
HW111How Computers Work$29.998
HW222Upgrading and Repairing PCs$59.995
HW333USB System Architecture$49.991
HW444Designing Embedded Hardware$44.953
HW555Contemporary Logic Design$102.952

Figure 7-16. Sorting a default GridView.
<asp:AccessDataSource id="BookSource" Runat="Server"
  DataFile="../Databases/eCommerce.mdb"
  SelectCommand="SELECT BookID, BookTitle, BookPrice, BookQty FROM Books
                 WHERE ItemType='Hardware' ORDER BY BookID"/>
	
<asp:GridView id="BookGrid" DataSourceID="BookSource" Runat="Server"
  AllowSorting="True"/>
Listing 7-16. Code to permit sorting of a default GridView.

Of course, you will likely wish to have more control over the output display and use bound columns rather than automatic columns. When setting AutoGenerateColumns="False" for the GridView, however, you must activate sorting for individual columns. This is done by adding the SortExpression="fieldname" property to all bound controls for which sorting is provided. The SortExpression names the sort field, normally the same data field as is displayed in the column. Use of sorted bound columns is shown in the example below.

IDTitlePriceQtyAmountOn Sale
HW111How Computers Work$29.998 239.92
HW222Upgrading and Repairing PCs$59.995 299.95
HW333USB System Architecture$49.991 49.99
HW444Designing Embedded Hardware$44.953 134.85
HW555Contemporary Logic Design$102.952 205.90

Figure 7-17. Sorting a GridView with bound columns.
<asp:AccessDataSource id="BookSource" Runat="Server"
  DataFile="../Databases/BooksDB.mdb"
  SelectCommand="SELECT * FROM Books WHERE BookType='Hardware'
                 ORDER BY BookID"/>
	
<asp:GridView id="BookGrid" DataSourceID="BookSource" Runat="Server"
  AllowSorting="True"
  AutoGenerateColumns="False"
  CellPadding="2"
  HeaderStyle-BackColor="#E0E0E0">

  <Columns>
	
  <asp:BoundField
    DataField="BookID"
    HeaderText="ID"
    SortExpression="BookID"/>
	
  <asp:BoundField
    DataField="BookTitle"
    HeaderText="Title"
    SortExpression="BookTitle"/>
	
  <asp:BoundField
    DataField="BookPrice"
    HeaderText="Price"
    SortExpression="BookPrice"
    ItemStyle-HorizontalAlign="Right"
    DataFormatString="{0:N2}"/>
	
  <asp:BoundField
    DataField="BookQty"
    HeaderText="Qty"
    SortExpression="BookQty"
    ItemStyle-HorizontalAlign="Right"
    DataFormatString="{0:N0}"/>
		
  <asp:TemplateField 
    HeaderText="Amount"
    ItemStyle-HorizontalAlign="Right" >
    <ItemTemplate>
      <asp:Label id="Amount" Runat="Server"
      Text='<%# Eval("BookPrice") * Eval("BookQty") %>'/>
    </ItemTemplate>
  </asp:TemplateField>
		
  <asp:CheckBoxField
    HeaderText="On Sale"
    DataField="BookSale"
    SortExpression="BookSale"
    ItemStyle-HorizontalAlign="Center"/>
		
  </Columns>

</asp:GridView>
Listing 7-17. Code to sort a GridView with BoundField columns.

Even TemplateFields can be sorted, although the SortExpression must name a database field, not be a calculation expression. In the above example, the TemplateField containing the calculated price-times-quantity amount is not sorted and does not supply a SortExpression. If, however, a TempleField is sorted by a data field, two rules must be followed. First, <HeaderTemplate> tags cannot be used to enclose the heading text. The text must be coded as a HeaderText property the TemplateField tag. Second, the SortExpression also must appear as a property of the TemplateField tag.

Notice in the case of the CheckBoxField that sorting arranges the records into two groups. Those that are checked and those that are unchecked appear together. An alternative is to identify a different sort field in the SortExpression, say, to arrange records by BookID when sorted on the checkbox column.

Paging a GridView

Often times, the amount of output displayed in a GridView is too large to fit conveniently on a single Web page without introducing an excessive amount of scrolling. There is a need to subdivide the output into more reasonably sized displays and permit paging through the table. This is exactly what can be achieved by adding AllowPaging="True" to a GridView. By default, 10 lines at a time are displayed. The PageSize="n" property can be added to the control to set the number of lines per page.

The following GridView shows paging in combination with sorting. Page numbers appear at the bottom of the table for scrolling through the recordset five items at a time. Notice that when sorting takes place the display is reset to the first page of output.

IDTitlePriceQtyAmountOn Sale
DB111Oracle Database$69.9910 699.90
DB222Databases in Depth$29.956 179.70
DB333Database Processing$136.6512 1,639.80
DB444Access Database Design$34.9525 873.75
DB555SQL Server 2005$29.990 0.00
123456

Figure 7-18. Paging a GridView with sorted columns.

A partial listing of the code for the above GridView is shown in Listing 7-18. Otherwise, it is the same code used for the previous display. AllowPaging="True" and PageSize="5" have been added to the control; also, all columns are given ItemStyle-Width settings so they remain the same widths when paging. Since columns widths are determined by the largest data item in the column, they can vary from page to page and become distracting.

<asp:GridView id="BookGrid" DataSourceID="BookSource" Runat="Server"
  AllowPaging="True"
  PageSize="5"
  AllowSorting="True"
  AutoGenerateColumns="False"
  ...>

  <Columns>

  <asp:BoundField
    DataField="BookID"
    HeaderText="ID"
    SortExpression="BookID"
    ItemStyle-Width="50"/>
  ...

  </Columns>

</asp:GridView>
Listing 7-18. Revised code to permit paging a GridView.

Pager Styling

By default, paging buttons are displayed as numeric links appearing at the bottom-left of the table. This style and positioning, along with other characteristics of the buttons, can be controlled through the PagerSettings- property added to the GridView. Available settings are shown in the following table.

PagerSettings- Description
FirstPageImageUrl="url" Sets the image to be used for first-page button.
FirstPageText="string" Sets the text to be used for first-page button.
LastPageImageUrl="url" Sets the image to be used for last-page button.
LastPageText="string" Sets the text to be used for last-page button.
Mode="NextPrevious|
      Numeric|
      NextPreviousFirstLast|
      NumericFirstLast"
Sets the display mode for text buttons.
NextPageImageUrl="url" Sets the image to be used for next-page button.
NextPageText="string" Sets the text to be used for next-page button.
PreviousPageImageUrl="url" Sets the image to be used for previous-page button.
PreviousPageText="string" Sets the text to be used for previous-page button.
PageButtonCount="n" Sets the number of text or image page buttons to display at a time.
Position="Bottom|
          Top|
          TopAndBottom"
Sets the location of paging buttons.
Visible="True|False" Sets the visibility of paging buttons.
Figure 7-19. Property values for PagerSettings attribute.

In addition to PagerSettings-, common server styles can be applied to pager buttons through the PagerStyle- property.

Below is shown the previous GridView table with several of these settings and styles applied, including using text in place of page numbers.

NextLast
IDTitlePriceQtyAmountOn Sale
DB111Oracle Database$69.9910 699.90
DB222Databases in Depth$29.956 179.70
DB333Database Processing$136.6512 1,639.80
DB444Access Database Design$34.9525 873.75
DB555SQL Server 2005$29.990 0.00
NextLast

Figure 7-20. Paging a GridView with styled paging buttons.
<asp:GridView id="BookGrid" DataSourceID="BookSource" Runat="Server"
  AllowPaging="True"
  PageSize="5"
  AllowSorting="True"
  AutoGenerateColumns="False"
  CellPadding="2"
  HeaderStyle-BackColor="#E0E0E0"

  PagerSettings-Position="TopAndBottom"
  PagerSettings-Mode="NextPreviousFirstLast"
  PagerSettings-FirstPageText="First"
  PagerSettings-PreviousPageText="Prev"
  PagerSettings-NextPageText="Next"
  PagerSettings-LastPageText="Last"

  PagerStyle-BackColor="#E0E0E0"
  PagerStyle-HorizontalAlign="Center"
>
   ...

</asp:GridView>
Listing 7-19. Code to page a GridView with styled paging buttons.

If you wish to create your own graphic images for use in place of page numbers or text, they can be easily included as PagerSettings. The following redesign of the previous GridView uses pager images that appear in the same folder as the page.

IDTitlePriceQtyAmountOn Sale
DB111Oracle Database$69.9910 699.90
DB222Databases in Depth$29.956 179.70
DB333Database Processing$136.6512 1,639.80
DB444Access Database Design$34.9525 873.75
DB555SQL Server 2005$29.990 0.00

Figure 7-21. Paging a GridView with graphic paging buttons.
<asp:GridView id="BookGrid" DataSourceID="BookSource" Runat="Server"
  AllowPaging="True"
  PageSize="5"
  AllowSorting="True"
  AutoGenerateColumns="False"
  CellPadding="2"
  HeaderStyle-BackColor="#E0E0E0"

  PagerSettings-Position="TopAndBottom"
  PagerSettings-Mode="NextPreviousFirstLast"
  PagerSettings-FirstPageImageUrl="First.gif"
  PagerSettings-PreviousPageImageUrl="Previous.gif"
  PagerSettings-NextPageImageUrl="Next.gif"
  PagerSettings-LastPageImageUrl="Last.gif"

  PagerStyle-BackColor="#E0E0E0"
  PagerStyle-HorizontalAlign="Center"
>
   ...

</asp:GridView>
Listing 7-20. Code to page a GridView with graphic paging buttons.