Displaying Data with the GridView Control


When we're displaying data on a web page, more often than not we want to display all records from a particular query. The query might be a static query, such as SELECT * FROM [Books], or it may be a more dynamic one whose filter expressions are based on the visitor's input. Regardless of the type of query, if you want to display all of the results at once, then consider using the GridView.

In addition to showing each of the records retrieved by the data source control, the GridView, by default, shows an additional header row, which lists the names of the displayed fields. By default, the GridView contains a field for each of the data source control's columns, although this can be customized as we'll see shortly.

In this hour we already examined adding a GridView to an ASP.NET page and associating it with a data source control. There are but two steps:

1.

Add a data source control to the page and configure it to retrieve the data you are interested in displaying.

2.

Add a GridView to the page and configure it to use the data source control added in step 1.

The result of these two simple steps is an ASP.NET page that displays the retrieved data in a grid.

A Look at the GridView's Declarative Markup

When adding the GridView control to our ASP.NET page, we did everything through the Design view. Like any other Web control, the GridView can also be configured declaratively, through the Source view. However, the tools available through the Design view can save you a great deal of typing. Figure 15.2 showed the Design view immediately after adding a GridView to the page. The declarative markup added to the Source view is very concise:

<asp:GridView  runat="server"> </asp:GridView> 


However, after you set the GridView's data source through the smart tag, the declarative markup explodes. Listing 15.1 contains the declarative markup after the GridView has been bound to SqlDataSource1. Figure 15.3 shows what the GridView looks like in the Design view after making this setting.

Listing 15.1. The GridView's Markup, After It's Been Bound to a Data Source Control

[View full width]

 1: <asp:GridView  runat="server" AutoGenerateColumns="False"  DataKeyNames="BookID"  2:     DataSource>  3:     <Columns>  4:         <asp:BoundField DataField="BookID" HeaderText="BookID" InsertVisible="False"  ReadOnly="True"  5:             SortExpression="BookID" />  6:         <asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title"/ >  7:         <asp:BoundField DataField="Author" HeaderText="Author" SortExpression="Author"/ >  8:         <asp:BoundField DataField="YearPublished" HeaderText="YearPublished"  SortExpression="YearPublished" />  9:         <asp:BoundField DataField="Price" HeaderText="Price" SortExpression="Price"/ > 10:         <asp:BoundField DataField="LastReadOn" HeaderText="LastReadOn"  SortExpression="LastReadOn" /> 11:         <asp:BoundField DataField="PageCount" HeaderText="PageCount"  SortExpression="PageCount" /> 12:     </Columns> 13: </asp:GridView> 

The <asp:GridView> tag (lines 1 and 2) has three new properties:

  • AutoGenerateColumns This property indicates whether the GridView bases its fields on the data source's columns or on the columns explicitly defined in the <Columns> tag. With AutoGenerateColumns="False", the fields rendered are those specified in the <Columns> tag.

  • DataKeyNames This property specifies the column name(s) that uniquely identify each row being bound to the GridView. This is, by default, the primary key column(s). The smart tag was able to determine the primary key of the data source control and assigned this property accordingly.

  • DataSourceID This property specifies the ID of the GridView's data source control.

Starting on line 3 is the <Columns> element, which defines the fields of the GridView (lines 4 through 11). Each <asp:BoundField> element represents a field rendered in the GridView. As you can see from Listing 15.1, there are seven fields in the GridView, one for each of the columns returned by the data source control. Each <asp:BoundField> element contains an assortment of properties, specifying the name of the database column whose data is to be displayed (DataField) and the text shown in the column's header (HeaderText), among others. This tag can also contain column-specific formatting information, as we'll see shortly.

The purpose of Listing 15.1 is to highlight the benefit of the Design view in Visual Web Developer. Without the Design view, we would have to enter in the GridView's declarative markup by hand. Thanks to the Design view and the GridView's smart tag, this declarative markup was automatically generated for us the moment we specified the GridView's data source control.

By the Way

In an upcoming section, "Customizing the Appearance of the GridView," we'll see how to tweak the aesthetic properties of the GridView through the Design view. Keep in mind, however, that you can always make the same changes through the declarative syntax, if needed. Granted, this approach might not be as easy or quick, but do keep in mind that there is a one-to-one correspondence between everything we do in the Design view and the resulting declarative markup of the control being edited.


Examining the GridView's Rendered Markup

When an ASP.NET page is requested through a browser, the page is rendered into HTML. This requires that the Web controls on the page be converted from the declarative markup to HTML. The GridView is translated into an HTML <table> with a table row (<tr>) for each row in the data source control and a table cell (<td>) for each column and for each row. The header row's columns are rendered as table headers (<th>).

Listing 15.2 shows the HTML generated by the GridView. When the browser receives this HTML, it will display the output shown in Figure 15.4.

Listing 15.2. A GridView Is Rendered as an HTML <table>

[View full width]

 1: <table cellspacing="0" rules="all" border="1"  style="border-collapse :collapse;">  2:   <tr>  3:     <th scope="col">BookID</th><th scope="col">Title</th><th scope="col">Author< /th><th scope="col">YearPublished</th><th scope="col">Price</th><th scope="col">LastReadOn< /th><th scope="col">PageCount</th>  4:   </tr><tr>  5:     <td>1</td><td>Visual Studio Hacks</td><td>James Avery</td><td>2005</td><td>24.9500< /td><td>&nbsp;</td><td>478</td>  6:   </tr><tr>  7:     <td>2</td><td>Create Your Own Website</td><td>Scott Mitchell</td><td>2005< /td><td>19.9900</td><td>8/1/2005 12:00:00 AM</td><td>195</td>  8:   </tr><tr>  9:     <td>3</td><td>The Number</td><td>Alex Berenson</td><td>2003</td><td>24.9500< /td><td>11/14/2005 12:00:00 AM</td><td>274</td> 10:   </tr><tr> 11:     <td>4</td><td>The Catcher in the Rye</td><td>J.D. Salinger</td><td>1991</td><td>6 .9500</td><td>6/12/2004 12:00:00 AM</td><td>224</td> 12:   </tr><tr> 13:     <td>5</td><td>Fight Club</td><td>Chuck Palahniuk</td><td>1999</td><td>16.9500< /td><td>&nbsp;</td><td>187</td> 14:   </tr> 15: </table> 

Customizing the Appearance of the GridView

The GridView shown in Figure 15.4 is rather unattractive. It lacks any color; uses the default system font; displays, perhaps, fields that don't concern the user (such as BookID); and lacks any sort of formatting for currency and date values. Also, all values are left-aligned and look alike. Perhaps we want the PageCount right-aligned and want to emphasize the title of the book by displaying it in italics. Finally, the field names displayed in the grid's header are the precise names of the database columnsBookID, YearPublished, LastReadOn, PageCount, and so on. Ideally, we would want these to be more readable names, like ID, Published, Last Read, and Pages.

All of these customizations can be easily accomplished with the GridView. The GridView allows customization of its appearance on a number of levels:

  • The GridView-level Changes specified at this level affect all of the data in the GridView.

  • The Field-level You can use this level to format a particular field in the GridView.

  • The Row-level You can specify customized formatting for various classes of rows. For example, you can make alternating rows have a different background color, or you can have the header row displayed in a larger font size.

These various levels of settings can be set through the Auto Format dialog box, the Fields dialog box, or the Properties window. Let's examine how to tailor the GridView's appearance at each of the levels using each of the tools available.

Formatting from the Properties Window

GridView-level and row-level formatting can be accomplished directly through the Properties window. Take a moment to click on the GridView in the Design view, which will load the GridView's properties in the Properties window. In the Appearances section (see Figure 15.5), you can set a number of GridView-level properties.

Figure 15.5. Customize the formatting of the entire GridView using the Appearance properties.


Table 15.1 lists these Appearance properties along with a brief description. Realize that these properties affect the entire GridView's formatting. That is, if you set, say, the BackColor property to Green, all of the rows and all of the fields in the GridView will have a Green background color.

Table 15.1. The Appearance Properties Affect the Entire GridView's Formatting

Property

Description

BackColor

Specifies the GridView's background color.

BackImageUrl

Specifies an image to display in the GridView's background.

BorderColor

Specifies the color of the GridView's border.

BorderStyle

Specifies the GridView's border's style. Can be NotSet, None, Dotted, Dashed, and Solid, among others.

BorderWidth

Specifies the width of the border.

CssClass

Specifies the class name if you want to apply an external cascading style sheet (CSS) class to the GridView.

EmptyDataText

Specifies whether you want a message to be displayed in the event that there are no records. Recall that a GridView is rendered only if there are records returned by its data source control.

Font

Specifies the font settings for the GridView. Refer to Table 8.1 for a listing of the Font property's subproperties.

ForeColor

Specifies the GridView's foreground color.

GridLines

Specifies how lines are drawn between the cells of the grid. Can be None, Vertical, Horizontal, or Both (the default).

ShowFooter

Specifies a Boolean value that indicates whether the footer row is shown; False by default.

ShowHeader

Specifies a Boolean value indicating whether the header row is shown; TRue by default.


Take a moment to try out some of these Appearance properties. Figure 15.5 shows Visual Web Developer after I set a number of properties. While making changes to these properties, notice how the GridView's appearance in the Design view is automatically updated to reflect the new formatting choices. Furthermore, note how the Appearance property settings affect the entire GridView.

The Properties window also includes properties that you can set to specify the formatting at the row-level. In the Styles section of the Properties window, you'll find a suite of properties that apply to various classes of rows. Table 15.2 lists these row-level style properties.

Table 15.2. The Styles Properties Affect Various Classes of Rows

Property

Description

AlternatingRowStyle

Specifies style information for alternating rows.

EditRowStyle

Specifies the formatting for an editable row. When you're working with an editable GridViewa topic for Hour 16, "Deleting, Inserting, and Editing Data"you will have a particular row being edited.

EmptyDataRowStyle

Specifies the style for a row if there are no records in the GridView's data source and you have set the EmptyDataText property in the Appearance settings.

FooterStyle

Specifies the style of the footer row.

HeaderStyle

Specifies the header row style.

PagerStyle

Specifies the style for the GridView's paging controls. When you're creating pageable GridViewsagain, a topic for Hour 16a pager row is included.

RowStyle

Specifies the style for a GridView row.

SelectedRowStyle

Specifies the style for a selected row. Unfortunately, we won't have time to examine how to make a GridView row "selected."


Each of these properties has a number of subproperties: BackColor, ForeColor, Font, CssClass, HorizontalAlign, and the like. Take a moment to set some of the subproperties for RowStyle, AlternatingRowStyle, and HeaderStyle. Figure 15.6 shows Visual Web Developer after I customized my GridView's formatting a bit.

Figure 15.6. The Styles properties allow you to customize various classes of rows.


Formatting the GridView's Fields

At this point we've seen how to perform GridView-level formatting as well as row-level formatting. The only level we've yet to examine is field-level. You cannot edit the fields of the GridView through the Properties window; instead, go to the GridView's smart tag and click the Edit Columns link. This will display the Fields dialog box (see Figure 15.7).

Figure 15.7. Customize the columns of the GridView through the Fields dialog box.


The Fields dialog box lists the fields in the GridView in the bottom-left corner. Selecting a field from this list will load that field's properties in the list on the right. At the upper-left portion of the Fields dialog box is the list of types of fields that can be added to a GridView. Currently, all of the fields used by the GridView are BoundFields. A BoundField simply displays the value from a particular column in the corresponding data source control. Other types of fields enable other functionality. For example, the HyperLinkField displays a hyperlink in each row; the ButtonField displays a button in each row. We'll examine some of these additional field types in more detail in Hour 16.

In addition to listing all of the fields currently in the GridView, the Selected Fields list allows you to remove fields and reorder the fields in the GridView. For example, let's remove the BookID field from the GridView because end users don't need this information. To remove this field from the GridView, click on the BookID field from the list in the bottom-left corner and then click the delete icon (the red X). Next, let's have the PageCount field displayed after the Author field. To accomplish this, click on the PageCount field and then click the up-arrow icon until PageCount is the third field in the list.

To customize a particular field, first click on the field in the list. This will load its properties in the right side of the dialog box. Table 15.3 lists some of the more germane field-level properties.

Table 15.3. A Field Can Be Customized Through the Fields Dialog Box

Property

Description

HeaderText

Specifies the text that is displayed in the field's header row.

DataFormatString

Indicates how the values for this field are formatted.

HtmlEncode

Specifies a Boolean value that indicates whether the value is HTML encoded before being bound to the grid (the default is true). HTML encoding is recommended because it removes <script> elements and other HTML that might not render properly in the grid. However, to have the DataFormatString property work, you must set HtmlEncode to False.

HeaderStyle

Specifies the field's header row style. You can customize the header row style on a field-by-field basis using this property.

ItemStyle

Indicates the style for the rows of the field. For example, you could have all of the book titles displayed in italics by setting this property for the Title field.


Change the HeaderText properties of the PageCount, YearPublished, and LastReadOn fields to Pages, Published and Last Read, respectively. Next, go to the Title field's ItemStyle property and expand it, locating the Font property. Expand the Font property and set the Italic subproperty to true.

Let's also configure the Price and LastReadOn fields to format their values more appropriately. To format a field, we need to set two properties: HtmlEncode must be set to False, and DataFormatString should be set to the format string of the form {0:format specifier}. The format specifier indicates how the data is to be formatted. A number of built-in format specifiers are designed to format specific data types. For example, c formats a number into a currency; d formats a date/time value into just a date. You can find a complete list of format specifiers by searching the Visual Web Developer help for "formatting."

To format the Price field as a currency and the LastReadOn field as just a date, set the HtmlEncode property to False for both fields and then set the DataFormatString properties of the Price field to {0:c} and the LastReadOn field to {0:d}.

Click OK to close the Fields dialog box. When you return to the Design view, the GridView should be updated to show the new changes: The BookID field has been removed, the Pages field now comes after the Author field, the Title field is displayed in italics, and so on. Figure 15.8 shows Internet Explorer when viewing the GridView after making these field-level formatting settings.

Figure 15.8. The fields of the GridView have been customized.


Formatting with the Auto Format Dialog Box

As you may have gathered from the formatting I've applied to the GridView, its rows, and its fields, I am hardly one to be trusted with choosing the GridView's formatting. I have about as much artistic skill as a vegetable. We can be thankful that the GridView includes an Auto Format option. From the smart tag, click the Auto Format link, which shows the Auto Format dialog box (see Figure 15.9). From this dialog box, you can pick one of a number of predefined styles.

Figure 15.9. The Mocha style looks so much nicer than anything I could craft.


Selecting one of the Auto Format styles will cause a number of Appearance and Styles properties to be automatically set in order to display the chosen format. If you are an artistic individual, you might rather just define these formatting settings yourself. However, if you're like me, the Auto Format feature will quickly become your best friend!




Sams Teach Yourself ASP. NET 2.0 in 24 Hours, Complete Starter Kit
Sams Teach Yourself ASP.NET 2.0 in 24 Hours, Complete Starter Kit
ISBN: 0672327384
EAN: 2147483647
Year: 2004
Pages: 233

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net