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.
<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"/>
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.
<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>
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.
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>
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.
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.
<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>
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.
<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>