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.

ItemNumberItemNameItemPriceItemQuantityItemSale
GR1111Photoshop CS589.9517
GR2222Illustrator CS359.956
GR3333Studio/MX 2004969.9513
GR4444Flash/MX 2004499.998
GR5555Creative Suites Premier 1.11109.9923
Figure 7-22. Sorting a default GridView.
<asp:AccessDataSource id="Products" Runat="Server"
  DataFile="../Databases/eCommerce.mdb"
  SelectCommand="SELECT ItemNumber, ItemName, ItemPrice, ItemQuantity FROM Products " & _
                "WHERE ItemType='Graphics'"/>
	
<asp:GridView id="ProductsGrid" DataSourceID="Products" 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.

NumberNamePriceQty.AmountOn Sale
GR1111Photoshop CS589.9517 10,029.15
GR2222Illustrator CS359.956 2,159.70
GR3333Studio/MX 2004969.9513 12,609.35
GR4444Flash/MX 2004499.998 3,999.92
GR5555Creative Suites Premier 1.11,109.9923 25,529.77
Figure 7-23. Sorting a GridView with bound columns.
<asp:AccessDataSource id="Products" Runat="Server"
  DataFile="../Databases/eCommerce.mdb"
  SelectCommand="SELECT * FROM Products WHERE ItemType='Graphics'"/>

<asp:GridView id="ProductsGrid" DataSourceID="Products" Runat="Server"
  AutoGenerateColumns="False"
  AllowSorting="True"
  CellPadding="3"
    HeaderStyle-BackColor="#707070"
    HeaderStyle-ForeColor="#FFFFFF">

  <Columns>

  <asp:BoundField
    SortExpression="ItemNumber"
    DataField="ItemNumber"
    HeaderText="Number"/>

  <asp:BoundField
    SortExpression="ItemName"
    DataField="ItemName"
    HeaderText="Name"/>

  <asp:BoundField
    SortExpression="ItemPrice"
    DataField="ItemPrice"
    HeaderText="Price"
    ItemStyle-HorizontalAlign="Right"
    DataFormatString="{0:N2}"/>

  <asp:BoundField
    SortExpression="ItemQuantity"
    DataField="ItemQuantity"
    HeaderText="Qty."
    ItemStyle-HorizontalAlign="Right"
    DataFormatString="{0:N0}"/>	

  <asp:TemplateField 
    HeaderText="Amount"
    SortExpression="ItemNumber"
    ItemStyle-HorizontalAlign="Right">
    <ItemTemplate>
      <asp:Label id="Amount" Runat="Server"
        Text='<%# FormatNumber(Eval("ItemPrice") * Eval("ItemQuantity")) %>'/>
      </ItemTemplate>
  </asp:TemplateField>

  <asp:CheckBoxField
    SortExpression="ItemSale"
    HeaderText="On Sale"
    DataField="ItemSale"
    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 calculated expression. In the above example, the TemplateField containing the calculated price-times-quantity amount sorts on the ItemNumber field. Of course, an option is not to provide a sort field for a calculated column. If, however, this is done, two rules must be followed. First, <HeaderTemplate> tags cannot be used to enclose the heading text. The header must be coded as a HeaderText property the TemplateField tag. Second, the SortExpression also must appear as a property of the TemplateField tag. Expression of these rules is shown in the above example.

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 ItemNumber 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 the 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.

NumberNamePriceQty.On Sale
BU1111Microsoft Office Professional 2003419.9920
BU2222WordPerfect Office 12210.2518
BU3333Project 2003519.9910
DB1111Access 2003194.9515
DB2222SQL Server 2000 Standard1,989.9510
1234
Figure 7-24. 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, bound columns are given 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="ProductsGrid" DataSourceID="Products" Runat="Server"
  AllowPaging="True"
  PageSize="5"
  AllowSorting="True"
  AutoGenerateColumns="False"
  ...>

  <Columns>

  <asp:BoundField
    SortExpression="ItemNumber"
    DataField="ItemNumber"
    HeaderText="Number"
    ItemStyle-HorizontalAlign="Center"
    ItemStyle-Width="60"/>
  ...

  </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 control. Available settings are shown in the following table.

PagerSettings-
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-25. 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
NumberNamePriceQty.On Sale
BU1111Microsoft Office Professional 2003419.9920
BU2222WordPerfect Office 12210.2518
BU3333Project 2003519.9910
DB1111Access 2003194.9515
DB2222SQL Server 2000 Standard1,989.9510
NextLast
Figure 7-26. Paging a GridView with styled paging buttons.
<asp:GridView id="ProductsGrid" DataSourceID="Products" Runat="Server"
  AllowPaging="True"
  PageSize="5"
  AllowSorting="True"
  AutoGenerateColumns="False"
  CellPadding="3"
    HeaderStyle-BackColor="#707070"
    HeaderStyle-ForeColor="#FFFFFF"

    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.

NumberNamePriceQty.On Sale
BU1111Microsoft Office Professional 2003419.9920
BU2222WordPerfect Office 12210.2518
BU3333Project 2003519.9910
DB1111Access 2003194.9515
DB2222SQL Server 2000 Standard1,989.9510
Figure 7-27. Paging a GridView with graphic paging buttons.
<asp:GridView id="ProductsGrid" DataSourceID="Products" Runat="Server"
  AllowPaging="True"
  PageSize="5"
  AllowSorting="True"
  AutoGenerateColumns="False"
  CellPadding="3"
    HeaderStyle-BackColor="#707070"
    HeaderStyle-ForeColor="#FFFFFF"

  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.