Using Fields with the GridView Control
In all the sample code in the previous section, the
GridView
control was used to automatically render an HTML table that contains a list of data items. However, there is a problem with allowing the
GridView
to render its
For example, the column headers are simply the
Another problem with enabling the GridView to render its columns automatically is that you give up any control over column formatting. For example, the BoxOfficeTotals column is displayed as a decimal amount without any currency formatting. The EnTRyDate column always displays in short-date and long-time format.
Furthermore, it would be nice to be able to display the values of certain columns as images, drop-down lists, or
The solution to all these problems is to specify explicitly the fields that a GridView displays. The GridView control supports the following types of fields:
The following sections examine how you can take advantage of each of these different types of fields.
Note You can create custom fields that work with the GridView control. This option is explored in the final section of this chapter. Using BoundFieldsA BoundField always displays the value of a data item as text when a row is in normal display mode. When a row is selected for editing, a BoundField displays the value of a data item in a single line text field. The most important three properties of the BoundField class are the DataField , DataFormatString , and HeaderText properties. The page in Listing 11.18 illustrates how to use these properties when displaying a list of movies (see Figure 11.13). Figure 11.13. Using BoundFields with the GridView control.
Listing 11.18. ShowBoundField.aspx
Notice that the GridView control includes an AutoGenerateColumns property that is assigned the value False . If you don't disable automatically generated columns, then both columns represented by the BoundFields and all the columns from the data source are displayed redundantly. In Listing 11.18, BoundFields are used to display the Title, Director, and BoxOfficeTotals columns. The DataField property is used to represent the column that a BoundField displays. The HeaderText property determines the column header. The BoundField used to display the BoxOfficeTotals column includes a DataFormatString property. This format string formats the values of the BoxOfficeTotals column as a currency amount. Notice that the BoundField also includes an HtmlEncode property that is set to the value False . When formatting a field, you need to prevent the GridView from encoding the field.
Warning When using the DataFormatString property, always set the HtmlEncode property to False . Otherwise, the formatting is not applied. This is a change from the previous version of ASP.NET.
Note For more information about string formatting, see the Formatting Types topic in the Microsoft .NET Framework SDK 2.0 documentation. A BoundField supports several other useful properties:
Using CheckBoxFieldsA CheckBoxField , as you can probably guess, displays a check box. When a row is not in edit mode, the check box is displayed but it is disabled. The page in Listing 11.19 illustrates how you can use a CheckBoxField (see Figure 11.14). Figure 11.14. Using the CHECKBOXFIELD with the GRIDVIEW control.
Listing 11.19. ShowCheckBoxField.aspx .
The CheckBoxField inherits from the BoundField class, so it includes all the properties of the BoundField class. It also supports the following property:
Using CommandFields
You can use a
CommandField
to customize the appearance of the Edit, Delete, Update, Cancel, and Select
Listing 11.20. ShowCommandField.aspx
Figure 11.15. Using a CommandField with the GridView control.
Notice that you do not enable the AutoGenerateEditButton or AutoGenerateDeleteButton properties when using a CommandField . Instead, you use the CommandField to set up the standard editing buttons explicitly. The CommandField supports the following properties:
Using Button FieldsYou use a ButtonField to display a button in a GridView . You can use a ButtonField to represent a custom command or one of the standard edit commands. For example, the GridView in Listing 11.21 contains two ButtonFields that a user can click to change the display order of the movie category records (see Figure 11.16). Listing 11.21. ShowButtonField.aspx
Figure 11.16. Using ButtonFields with the GridView control.
When you click either the Move Up or Move Down buttons in the page in Listing 11.21, the GridView control's RowCommand event is raised. This event is handled by the grdMovieCategories_RowCommand() method. The grdMovieCategories_RowCommand() retrieves the index of the row containing the button that was clicked. The row index is grabbed from the GridViewCommandEventArgs 's CommandArgument property passed as the second parameter to the event handler. The grdMovieCategories_RowCommand() method updates the position of a record by setting the SqlDataSource control's Update parameters and calling the SqlDataSource control's Update() method. A ButtonField supports the following properties:
Notice that you can use CommandName to associate a ButtonField with one of the standard edit commands. For example, you can create a Delete button by assigning the value Delete to the CommandName property. Using HyperLinkFieldYou use a HyperLinkField to create a link to another page. A HyperLinkField is particularly useful when you need to build two page Master/Detail forms. For example, the page in Listing 11.22 displays a list of movie categories, and the page in Listing 11.23 displays a list of movies that match the selected category. Listing 11.22. Master.aspx
Listing 11.23. Details.aspx
The page in Listing 11.22 includes a
GridView
control that contains a
HyperLinkField
. The
HyperLinkField
creates a link to the
Details.aspx
page and
The HyperLinkField looks like this:
<asp:HyperLinkField
HeaderText="Movie Categories"
DataTextField="Name"
DataNavigateUrlFields="Id"
DataNavigateUrlFormatString="Details.aspx?id={0}" />
The DataNavigateUrlFields property represents the fields used with the DataNavigateFormatString . The DataNavigateFormatString plugs the value of the ID column from the DataNavigateUrlFields into the {0} placeholder.
Note The DataNavigateUrlFields property accepts a comma-separated list of column names. You can use multiple placeholders in the DataNavigateUrlFormatString . When you link to the page in Listing 11.23, the list of matching movies is displayed. Notice that the SqlDataSource control includes a QueryStringParameter that represents the movie category ID query string parameter.
You also can use
HyperLinkFields
when working with
Figure 11.17. Displaying a
|
<%@ Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<style type="text/css">
html
{
background-color:silver;
}
.content
{
width:500px;
margin:auto;
background-color:white;
}
.column
{
padding:10px;
float:left;
}
#FrameDetails
{
width:100%;
height:400px;
}
</style>
<title>Frame Master</title>
</head>
<body>
<form id="form1" runat="server">
<div class="content">
<div class="column">
<asp:GridView
id="grdMovies"
DataSourceID="srcMovies"
AutoGenerateColumns="false"
Runat="server">
<Columns>
<asp:HyperLinkField
HeaderText="Movies"
DataTextField="Title"
DataNavigateUrlFields="Id"
DataNavigateUrlFormatString="FrameDetails.aspx?id={0}"
Target="FrameDetails" />
</Columns>
</asp:GridView>
<asp:SqlDataSource
id="srcMovies"
ConnectionString="<%$ ConnectionStrings:Movies %>"
SelectCommand="SELECT * FROM Movies"
Runat="server" />
</div>
<div class="column">
<iframe name="FrameDetails" id="FrameDetails"></iframe>
</div>
<br style="clear:both" />
</div>
</form>
</body>
</html>
|
<%@ Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Frame Details</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DetailsView
id="dtlMovie"
DataSourceID="srcMovieDetails"
Runat="server" />
<asp:SqlDataSource
id="srcMovieDetails"
ConnectionString="<%$ ConnectionStrings:Movies %>"
SelectCommand="SELECT Title, Director, InTheaters
FROM Movies WHERE Id=@MovieId"
Runat="server">
<SelectParameters>
<asp:QueryStringParameter
Name="MovieId"
QueryStringField="id" />
</SelectParameters>
</asp:SqlDataSource>
</div>
</form>
</body>
</html>
|
Notice that the HyperLinkField contained in Listing 11.24 includes a Target property. The Target property contains the name of the iframe. When you click a movie link, the FrameDetails.aspx page opens in the named iframe .
The HyperLinkField supports the following properties:
DataNavigateUrlFields Represents the field or fields from the data source to use with the DataNavigateUrlFormatString .
DataNavigateUrlFormatString Represents a format string that can be used to create the hyperlink.
DataTextField Represents a field from the data source to use for the hyperlink label.
DataTextFormatString Represents a format string that can be used to format the hyperlink label.
NavigateUrl Represents a fixed link to another page.
Target Represents the target of a link. Possible values include _blank , _parent , _self , and _top . You can also supply the name of a frame or iframe.
Text Represents fixed text to display as the label for the hyperlink.
You use an ImageField to display an image stored on the server's hard drive. You can't use an ImageField to display images stored in a database table.
The page in Listing 11.26 illustrates how you can use the ImageField when creating a simple photo gallery (see Figure 11.18).
|
[View full width]
<%@ Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<script runat="server">
Protected Sub frmPhoto_ItemInserting(ByVal sender As Object, ByVal e As
|
The GridView in Listing 11.26 contains an ImageField that looks like this:
<asp:ImageField
DataImageUrlField="FileName"
DataImageUrlFormatString="~/Photos/{0}"
DataAlternateTextField="AltText"
ControlStyle-Width="200px" />
The
DataImageUrlField
property contains the name of a field from the data source that represents the
Web Standards Note
Always supply an
alt
attribute for your
<img>
tags so that blind users of your web application can interpret an image's meaning. In the case of purely
An ImageField supports the following properties:
AlternateText Enables you to specify fixed alternate text.
DataAlternateTextField Enables you to specify a field that represents the alternate text.
DataAlternateTextFormatString Enables you to format the alternate text.
DataImageUrlField Enables you to specify a field that represents the image path.
DataImageUrlFormatString Enables you to format the image path.
NullImageUrl Enables you to specify an alternate image when the DataImageUrlField is Nothing (null).
A TemplateField enables you to add any content to a GridView column that you need. A TemplateField can contain HTML, DataBinding expressions, or ASP.NET controls.
TemplateFields are particularly useful when you are using a GridView to edit database records. You can use a TemplateField to customize the user interface and add validation to the fields being edited.
For example, the page in Listing 11.27 contains a GridView that enables you to edit the records contained in the Movies database table. TemplateField s are used to render the user interface for editing the movie title and category columns (see Figure 11.19).
<%@ Page Language="VB" %>
<!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>Show TemplateField</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView
id="grdMovies"
DataSourceID="srcMovies"
DataKeyNames="Id"
AutoGenerateColumns="false"
AutoGenerateEditButton="true"
Runat="server">
<Columns>
<asp:TemplateField HeaderText="Title">
<ItemTemplate>
<%# Eval("Title") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox
id="txtTitle"
Text='<%# Bind("Title") %>'
Runat="server" />
<asp:RequiredFieldValidator
id="valTitle"
ControlToValidate="txtTitle"
Text="(required)"
Runat="server" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Category">
<ItemTemplate>
<%# Eval("Name") %>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList
id="ddlCategory"
DataSourceID="srcMovieCategories"
DataTextField="Name"
DataValueField="Id"
SelectedValue='<%# Bind("CategoryId") %>'
Runat="server" />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource
id="srcMovies"
ConnectionString='<%$ ConnectionStrings:Movies %>'
SelectCommand="SELECT Movies.Id, Title, CategoryId, Name
FROM Movies JOIN MovieCategories
ON MovieCategories.Id = Movies.CategoryId"
UpdateCommand="UPDATE Movies SET Title=@Title, CategoryId=@CategoryId
WHERE Id=@Id"
Runat="server" />
<asp:SqlDataSource
id="srcMovieCategories"
ConnectionString='<%$ ConnectionStrings:Movies %>'
SelectCommand="SELECT Id, Name FROM MovieCategories"
Runat="server" />
</div>
</form>
</body>
</html>
|
The GridView in Listing 11.27 contains two TemplateField s. The first TemplateField enables you to display and edit the value of the Title column. The contents of the ItemTemplate are displayed when a row is not selected for editing. The contents of the EditItemTemplate are displayed when the row is selected for editing.
The
EditItemTemplate
for the Title column includes a
RequiredFieldValidator
control. This
RequiredFieldValidator
control
The second TemplateField displays the value of the movie category column. The EditItemTemplate contains a DropDownList control, which enables you to change the movie category associated with the record being edited.
A TemplateField supports the following six types of templates:
AlternatingItemTemplate The contents of this template are displayed for every other row rendered by the GridView .
EditItemTemplate The contents of this template are displayed when a row is selected for editing.
FooterTemplate The contents of this template are displayed in the column footer.
HeaderTemplate The contents of this template are displayed in the column header.
InsertItemTemplate The contents of this template are displayed when a new data item is inserted (does not apply to the GridView control).
ItemTemplate The contents of this template are displayed for every row rendered by the GridView .