Sorting Data You can sort the rows rendered by a GridView control by enabling the AllowSorting prop-erty.. When you click a column header, you can sort the rows contained in the GridView
Trang 1<br style=”clear:both” />
</div>
<asp:SqlDataSource
id=”srcEmployees”
ConnectionString=”<%$ ConnectionStrings:Employees %>”
SelectCommand=”SELECT LastName,FirstName
FROM Employees”
Runat=”server” />
<asp:SqlDataSource
id=”srcEmployeeDetails”
ConnectionString=”<%$ ConnectionStrings:Employees %>”
SelectCommand=”SELECT * FROM Employees
WHERE FirstName=@FirstName AND LastName=@LastName”
Runat=”server”>
<SelectParameters>
<asp:ControlParameter
Name=”FirstName”
ControlID=”grdEmployees”
PropertyName=’SelectedDataKey(“FirstName”)’ />
<asp:ControlParameter
Name=”LastName”
ControlID=”grdEmployees”
PropertyName=’SelectedDataKey(“LastName”)’ />
</SelectParameters>
</asp:SqlDataSource>
</form>
</body>
</html>
In Listing 11.4, the SelectedDataKey() method retrieves the primary key of the selected
employee The SelectedDataKey() method is used in both of the ControlParameters
contained in the second SqlDataSource control If you use SelectedValue() instead of
SelectedDataKey(),you can return only the value of the first data key and not both
values
A GridView stores data keys in a collection called the DataKeys collection This collection
is exposed by the GridView control’s DataKeys property You can retrieve the data key
asso-ciated with any row by using a statement that looks like this:
Object key = GridView1.DataKeys[6].Value;
Trang 2This statement returns the value of the data key associated with the seventh row in the
GridView (Remember that the rows collection is zero-based.) If you have assigned
multi-ple data keys to each row, you can use a statement that looks like this:
Object key = GridView1.DataKeys[6].Values[“LastName”];
This statement retrieves the value of the LastName key for the seventh row in the
GridView
Sorting Data
You can sort the rows rendered by a GridView control by enabling the AllowSorting
prop-erty For example, the page in Listing 11.5 illustrates how you can sort the contents of the
Movies database table
LISTING 11.5 SortGrid.aspx
<%@ Page Language=”C#” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”
“http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml” >
<head id=”Head1” runat=”server”>
<title>Sort Grid</title>
</head>
<body>
<form id=”form1” runat=”server”>
<div>
<asp:GridView
id=”grdMovies”
DataSourceID=”srcMovies”
AllowSorting=”true”
Runat=”server” />
<asp:SqlDataSource
id=”srcMovies”
ConnectionString=”<%$ ConnectionStrings:Movies %>”
SelectCommand=”SELECT Id,Title,DateReleased FROM Movies”
Runat=”server” />
</div>
</form>
</body>
</html>
Trang 3When AllowSorting has the value True, column headers render as links When you click a
column header, you can sort the rows contained in the GridView in the order of the
selected column
NOTE
When using explicitly specified fields with a GridView, such as BoundFields, you need
to specify values for the fields’ SortExpression properties Otherwise, nothing
hap-pens when you click a header
The GridView supports ascending and descending sorts In other words, if you click a
column header more than once, the rows toggle between being sorted in ascending and
descending order
Sorting with AJAX
By default, whenever you click a column header to sort the rows contained in a GridView,
the page containing the GridView is posted back to the server When sorting records with
the GridView control, you can avoid posting the entire page back to the server by taking
advantage of Ajax (Asynchronous JavaScript and XML)
We get into the details of Ajax in Part IX, “ASP.NET AJAX.” In this section, I provide you
with a quick code sample that demonstrates how to use Ajax with the GridView control
The page in Listing 11.6 illustrates how you can take advantage of AJAX when sorting
records
LISTING 11.6 AjaxSorting.aspx
<%@ Page Language=”C#” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”
“http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml” >
<head id=”Head1” runat=”server”>
<title>AJAX Sorting</title>
</head>
<body>
<form id=”form1” runat=”server”>
<div>
<asp:ScriptManager ID=”sm1” runat=”server” />
<%= DateTime.Now.ToString(“T”) %>
<asp:UpdatePanel ID=”up1” runat=”server”>
<ContentTemplate>
Trang 4id=”grdMovies”
DataSourceID=”srcMovies”
AllowSorting=”true”
EnableSortingAndPagingCallbacks=”true”
Runat=”server” />
</ContentTemplate>
</asp:UpdatePanel>
<asp:SqlDataSource
id=”srcMovies”
ConnectionString=”<%$ ConnectionStrings:Movies %>”
SelectCommand=”SELECT Id,Title,DateReleased FROM Movies”
Runat=”server” />
</div>
</form>
</body>
</html>
GridView in Listing 11.6 is contained in an UpdatePanel control When you sort GridView,
only the region of the page contained in the UpdatePanel is updated
The current time displays at the top of the page The time is not updated when you sort
the records in GridView The entire page is not posted back to the server; only the content
of the UpdatePanel control is updated
NOTE
An alternative method for Ajax sorting with the GridView control is to enable the
GridView control’s EnableSortingAndPagingCallbacks property I don’t suggest that
you use this method because it limits the types of fields that you can add to
GridView For example, if you enable EnableSortingAndPagingCallbacks, you can’t
use TemplateFields with GridView The UpdatePanel control is not subject to these
same limitations
Customizing the Sorting Interface
You can customize the appearance of the sort links by handling the GridView control’s
RowDataBound event This event is raised for each row rendered by GridView after GridView
is bound to its data source
For example, the page in Listing 11.7 displays an image that represents whether a column
is sorted in ascending or descending order (see Figure 11.4)
Trang 5LISTING 11.7 ImageSorting.aspx
<%@ Page Language=”C#” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”
“http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>
<script runat=”server”>
protected void grdMovies_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
foreach (TableCell cell in e.Row.Cells)
{
LinkButton sortLink = (LinkButton)cell.Controls[0];
if (sortLink.Text == grdMovies.SortExpression) {
if (grdMovies.SortDirection == SortDirection.Ascending) sortLink.Text += “ <img src=’asc.gif’ title=’Sort
➥ascending’ />”;
else sortLink.Text += “ <img src=’desc.gif’ title=’Sort
➥descending’ />”;
FIGURE 11.4 Displaying an image when sorting
Trang 6} }
}
}
</script>
<html xmlns=”http://www.w3.org/1999/xhtml” >
<head id=”Head1” runat=”server”>
<style type=”text/css”>
img
{
border:0px;
}
</style>
<title>Image Sorting</title>
</head>
<body>
<form id=”form1” runat=”server”>
<div>
<asp:GridView
id=”grdMovies”
DataSourceID=”srcMovies”
AllowSorting=”true”
Runat=”server” OnRowDataBound=”grdMovies_RowDataBound” />
<asp:SqlDataSource
id=”srcMovies”
ConnectionString=”<%$ ConnectionStrings:Movies %>”
SelectCommand=”SELECT Id,Title,Director FROM Movies”
Runat=”server” />
</div>
</form>
</body>
</html>
In Listing 11.7, the image is added to the header row in the grdMovies_RowDataBound()
method The current row’s RowType property is checked to verify that the row is a header
row Next, an HTML <img> tag is added to the LinkButton that matches the column
currently selected for sorting
If you need to completely customize the appearance of the sorting user interface, you can
call the GridView control’s Sort() method programmatically Listing 11.8 illustrates this
approach (see Figure 11.5)
Trang 7LISTING 11.8 CustomSorting.aspx
<%@ Page Language=”C#” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”
“http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>
<script runat=”server”>
protected void btnSort_Click(object sender, EventArgs e)
{
grdMovies.Sort(ddlSort.Text, SortDirection.Ascending);
}
</script>
<html xmlns=”http://www.w3.org/1999/xhtml” >
<head id=”Head1” runat=”server”>
<title>Custom Sorting</title>
</head>
<body>
<form id=”form1” runat=”server”>
<div>
FIGURE 11.5 Displaying a custom sorting interface
Trang 8<asp:DropDownList
id=”ddlSort”
Runat=”server”>
<asp:ListItem Text=”Id” />
<asp:ListItem Text=”Title” />
<asp:ListItem Text=”Director” />
</asp:DropDownList>
<asp:Button
id=”btnSort”
Text=”Sort”
Runat=”server” OnClick=”btnSort_Click” />
<asp:GridView
id=”grdMovies”
DataSourceID=”srcMovies”
Runat=”server” />
<asp:SqlDataSource
id=”srcMovies”
ConnectionString=”<%$ ConnectionStrings:Movies %>”
SelectCommand=”SELECT Id,Title,Director FROM Movies”
Runat=”server” />
</div>
</form>
</body>
</html>
The page in Listing 11.8 includes a DropDownList control, which you can use to sort the
contents of the GridView When a list item is selected from the DropDownList control and
the Sort button is clicked, the btnSort_Click() method executes This method calls the
Sort() method of the GridView control to sort the contents of GridView
Paging Through Data
When working with a large number of database rows, it is useful to display the rows in
different pages You can enable paging with the GridView control by enabling its
AllowPaging property
For example, the page in Listing 11.9 enables you to page through the records in the
Movies database table (see Figure 11.6)
Trang 9LISTING 11.9 PageGrid.aspx
<%@ Page Language=”C#” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”
“http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml” >
<head id=”Head1” runat=”server”>
<title>Page Grid</title>
</head>
<body>
<form id=”form1” runat=”server”>
<div>
<asp:GridView
id=”grdMovies”
DataSourceID=”srcMovies”
AllowPaging=”true”
PageSize=”3”
Runat=”server” />
<asp:SqlDataSource
id=”srcMovies”
FIGURE 11.6 Paging through records in a GridView control
Trang 10ConnectionString=”<%$ ConnectionStrings:Movies %>”
SelectCommand=”SELECT Id,Title,Director FROM Movies”
Runat=”server” />
</div>
</form>
</body>
</html>
The GridView in Listing 11.9 displays three database records per page You can modify the
number of records displayed per page by modifying the GridView control’s PageSize
prop-erty (If you don’t specify a value for PageSize, the GridView defaults to displaying 10
records per page.)
WARNING
This section describes how you can enable user interface paging with the GridView
control When you use user interface paging, all the database records load into
memo-ry and divide into separate pages For example, when paging through a database table
that contains three billion database records, all three billion records load into memory
even when you display only three records in a single page You should not use user
interface paging when working with large sets of data Instead, use the
ObjectDataSource control’s support for data source paging This option is
discussed in Chapter 18, “Using the ObjectDataSource Control.”
Paging with AJAX
The default behavior of the GridView control is to post back to the server every time you
navigate to a new page of records; however, there is an alternative You can take advantage
of AJAX when paging through records with the GridView control
The page in Listing 11.10 illustrates how you can use AJAX with the GridView control
LISTING 11.10 AjaxPaging.aspx
<%@ Page Language=”C#” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”
“http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml” >
<head id=”Head1” runat=”server”>
<title>AJAX Page</title>
</head>
<body>
<form id=”form1” runat=”server”>
<div>