ptg
484
CHAPTER 10 Using List Controls
<hr />
<asp:Label
id=”lblSelected”
EnableViewState=”false”
Runat=”server” />
</div>
</form>
</body>
</html>
In the page in Listing 10.19, the MultiSelectList control is bound to a SqlDataSource
control, which represents the contents of the Movies database table. You can select movie
titles in the MultiSelectList control by moving movie titles from one list box to the
second list box. When you click the Submit button, the selected movies display in a Label
control.
Summary
In this chapter, you learned how to use List controls to display simple option lists. You saw
the DropDownList, RadioButtonList, ListBox, CheckBoxList, and BulletedList controls.
You also saw the common features of the List controls. You learned how to append data
items to a List control and automatically post a form containing a List control back to
the server.
Finally, you worked through the creation of a custom List control, which involved deriv-
ing a new control from the base ListControl class. The custom List control takes advan-
tage of client-side JavaScript to enable users to select multiple list items without requiring
a page to post back to the server when each item is selected.
From the Library of Wow! eBook
ptg
CHAPTER 11
Using the GridView
Control
IN THIS CHAPTER
. GridView Control
Fundamentals
. Using Fields with the Gridview
Control
. Working with GridView Control
Events
. Extending the GridView
Control
. Summary
The GridView control is the workhorse of ASP.NET
Framework. It is one of the most feature-rich and compli-
cated of all the ASP.NET controls. The GridView control
enables you to display, select, sort, page, and edit data items
such as database records.
NOTE
The GridView control supersedes the DataGrid
control included in the ASP.NET 1.x Framework. The
DataGrid control is still included in ASP.NET 4 for
backward compatibility, but you should use the
GridView instead because it is a more powerful
control.
In this chapter, you learn everything you ever wanted to
know about the GridView control. You learn how to use all
the basic features of the GridView control. For example, you
learn how to use this control to display, select, sort, page,
and edit database records. You also learn how to use AJAX
with the GridView control when sorting and paging records.
You also get the chance to tackle several advanced topics.
For example, you learn how to highlight certain rows in a
GridView depending on the data the row represents. You
also learn how to display column summaries.
Finally, you learn how to extend the GridView control by
building custom GridView fields. At the end of this chapter,
we build a LongTextField, a DeleteButtonField, and a
ValidatedField.
From the Library of Wow! eBook
ptg
486
CHAPTER 11 Using the GridView Control
GridView Control Fundamentals
In this section, you learn how to take advantage of all the basic features of the GridView
control. In particular, you learn how to display, select, sort, page, and edit database data
with a GridView control. We also discuss GridView formatting options.
Displaying Data
GridView renders its data items in an HTML table. Each data item renders in a distinct
HTML table row. For example, the page in Listing 11.1 demonstrates how you can use
GridView to display the contents of the Movies database table (see Figure 11.1).
LISTING 11.1 ShowMovies.aspx
<%@ Page Language=”C#” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”
“
<html xmlns=” >
<head id=”Head1” runat=”server”>
<title>Show Movies</title>
</head>
<body>
FIGURE 11.1 Displaying data with the GridView control.
From the Library of Wow! eBook
ptg
487
Gridview Control Fundamentals
11
<form id=”form1” runat=”server”>
<div>
<asp:GridView
id=”grdMovies”
DataSourceID=”srcMovies”
Runat=”server” />
<asp:SqlDataSource
id=”srcMovies”
ConnectionString=”<%$ ConnectionStrings:Movies %>”
SelectCommand=”SELECT Id,Title,Director,InTheaters,DateReleased
FROM Movies”
Runat=”server” />
</div>
</form>
</body>
</html>
In Listing 11.1, the GridView control is bound to a SqlDataSource control, which repre-
sents the Movies database table. The GridView associates with its data source through its
DataSourceID property.
The GridView control automatically renders a check box for any Boolean fields. In the case
of Listing 11.1, GridView renders a check box for the InTheaters database column. For all
other types of fields, GridView simply renders the contents of the field.
WEB STANDARDS NOTE
The GridView control was designed to meet XHTML and accessibility guidelines. For
example, the control uses the <th> tag to render its headers. Furthermore, each head-
er tag includes a scope=”col” attribute.
VISUAL WEB DEVELOPER NOTE
You can add a GridView and SqlDataSource control to a page quickly by dragging a
database table from the Database Explorer window onto a page in Design view. When
you drag a database table onto the page, a SqlDataSource is automatically created,
which retrieves all the rows and all the columns from a database table.
From the Library of Wow! eBook
ptg
488
The GridView control also supports programmatic databinding. In Listing 11.2, the
GridView control displays a list of shopping list items represented by a Generic List
collection.
LISTING 11.2 ShowShoppingList.aspx
<%@ Page Language=”C#” %>
<%@ Import Namespace=”System.Collections.Generic” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”
“
<script runat=”server”>
void Page_Load()
{
// Build shopping list
List<string> shoppingList = new List<string>();
shoppingList.Add(“Bread”);
shoppingList.Add(“Milk”);
shoppingList.Add(“Beer”);
shoppingList.Add(“Waffles”);
// Bind to GridView
grdShoppingList.DataSource = shoppingList;
grdShoppingList.DataBind();
}
</script>
<html xmlns=” >
<head id=”Head1” runat=”server”>
<title>Show Shopping List</title>
</head>
<body>
<form id=”form1” runat=”server”>
<div>
<asp:GridView
id=”grdShoppingList”
Runat=”server” />
</div>
</form>
</body>
</html>
CHAPTER 11 Using the GridView Control
From the Library of Wow! eBook
ptg
489
Gridview Control Fundamentals
11
GridView is bound to the shopping list in the Page_Load() method. Its DataSource prop-
erty points to the List collection, and its DataBind() method is called to load the items
from the List collection and display them.
Selecting Data
You can allow a user to select a particular row in a GridView control. This is useful when
you want to build single-page Master/Details forms. For example, the page in Listing 11.3
contains two GridView controls. The first GridView displays a list of movie categories.
When you select a category, the second GridView displays a list of matching movies (see
Figure 11.2).
FIGURE 11.2 Selecting a GridView row.
LISTING 11.3 SelectGridView.aspx
<%@ Page Language=”C#” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”
“
<html xmlns=” >
<head id=”Head1” runat=”server”>
<style type=”text/css”>
html
{
background-color:silver;
From the Library of Wow! eBook
ptg
490
font-family:Georgia, Serif;
}
.gridView
{
float:left;
margin-right:20px;
background-color:white;
}
.gridView td, .gridView th
{
padding:10px;
}
.selectedRow
{
background-color:yellow;
}
</style>
<title>Select GridView</title>
</head>
<body>
<form id=”form1” runat=”server”>
<div>
<asp:GridView
id=”grdMovieCategories”
DataKeyNames=”Id”
DataSourceID=”srcMovieCategories”
AutoGenerateSelectButton=”true”
SelectedRowStyle-CssClass=”selectedRow”
CssClass=”gridView”
Runat=”server” />
<asp:GridView
id=”grdMovies”
DataSourceID=”srcMovies”
CssClass=”gridView”
Runat=”server” />
<asp:SqlDataSource
id=”srcMovieCategories”
ConnectionString=”<%$ ConnectionStrings:Movies %>”
SelectCommand=”SELECT Id, Name FROM MovieCategories”
Runat=”server” />
CHAPTER 11 Using the GridView Control
From the Library of Wow! eBook
ptg
491
Gridview Control Fundamentals
11
<asp:SqlDataSource
id=”srcMovies”
ConnectionString=”<%$ ConnectionStrings:Movies %>”
SelectCommand=”SELECT Title,Director FROM Movies
WHERE CategoryId=@CategoryId”
Runat=”server”>
<SelectParameters>
<asp:ControlParameter
Name=”CategoryId”
ControlID=”grdMovieCategories”
PropertyName=”SelectedValue” />
</SelectParameters>
</asp:SqlDataSource>
</div>
</form>
</body>
</html>
The first GridView has its AutoGenerateSelectButton property enabled. When this prop-
erty has the value True, a Select link displays next to each row.
You can determine which row is selected in a GridView control by using any of the follow-
ing methods:
. SelectedDataKey()—Returns the DataKey object associated with the selected row.
(This is useful when there are multiple data keys.)
. SelectedIndex()—Returns the (zero-based) index of the selected row.
. SelectedValue()—Returns the data key associated with the selected row.
. SelectedRow()—Returns the actual row (GridViewRow object) associated with the
selected row.
In most cases, you use the SelectedValue() method to determine the value associated
with a particular row. The SelectedValue() method returns the data key associated with a
row. The following section discusses data keys.
NOTE
When a user changes the page in GridView, you might not want the selected row to
remain in the selected state when new data populates. You can set the
PersistedSelection property to True to avoid this. When the user changes a
GridView page, the selection goes away, and if they go back to the original page, the
selection reappears.
From the Library of Wow! eBook
ptg
492
Using Data Keys
You associate a value with each row in a GridView by providing a value for the GridView
control’s DataKeyNames property. You can assign the name of a single database column to
this property, or you can assign a comma-separated list of column names to this property.
For example, the Employees database table uses two columns—the employee first and last
name—as a primary key. The page in Listing 11.4 displays employee details when you
select a particular employee (see Figure 11.3).
CHAPTER 11 Using the GridView Control
FIGURE 11.3 Displaying employee details.
LISTING 11.4 SelectDataKeys.aspx
<%@ Page Language=”C#” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”
“
<html xmlns=” >
<head id=”Head1” runat=”server”>
<style type=”text/css”>
html
{
background-color:silver;
}
.content
{
From the Library of Wow! eBook
ptg
493
Gridview Control Fundamentals
11
width:600px;
margin:auto;
background-color:white;
}
.column
{
float:left;
padding:10px;
width:265px;
}
.column td,.column th
{
padding:5px;
font:14px Georgia, Serif
}
.selectedRow
{
background-color:yellow;
}
</style>
<title>Select Data Keys</title>
</head>
<body>
<form id=”form1” runat=”server”>
<div class=”content”>
<div class=”column”>
<asp:GridView
id=”grdEmployees”
DataSourceID=”srcEmployees”
DataKeyNames=”LastName,FirstName”
AutoGenerateSelectButton=”true”
SelectedRowStyle-CssClass=”selectedRow”
Runat=”server” />
</div>
<div class=”column”>
<asp:DetailsView
id=”dtlEmployees”
DataSourceID=”srcEmployeeDetails”
Runat=”server” />
</div>
From the Library of Wow! eBook