Dynamic, data-driven Web sites produce most of their content from external data repositories, most notably from databases. This is especially the case for commercial Web sites and intranets, where content is drawn from the databases that store information on an enterprise's products and services for sale and on its financial, operational, and management control activities.
Consider, for instance, any commercial Web site with products for sale. Product information certainly cannot be hard-coded on Web pages for presentation to the public. There are just too many products whose description, availability, and pricing change routinely to have to continually revise pages manually to keep the information up to date. Besides, this information already exists in company databases where it is maintained in the normal course of doing business. The better solution for Web presentation is to draw this information directly from these data repositories. Web pages can link to these databases to extract and present live information about products without any need to edit the pages to keep their information current.
The Web page developer, then, has recurring need for mechanisms to link to all manner of databases to extract information and present it in organized form for page display. As described previously, ASP.NET provides data access controls for convenient connections to external data sources. It also provides several information display controls especially designed to present this information on a Web page. This and follow-up tutorials describe the information display controls that are new to ASP.NET 2.0. Later tutorials cover display controls that existed previously and have been carried forward under this new development environment.
A Basic GridView
An <asp:GridView> control is the most powerful of the server controls used to display external data. It is especially designed to work with database tables, but can provide display of other relational data sources organized into rows and columns. It is also designed for use with data source controls so that little or no scripting is required to populate the control with database information. The GridView includes features for editing of databases as well as for their display. The present focus, however, is on using the control for presentation of information. Its basic layout and formatting options are shown in Figure 7-1.
<asp:GridView id="id" Runat="Server" AllowPaging="False|True" AllowSorting="False|True" AutoGenerateColumns="False|True" Caption="string" CaptionAlign="Top|Bottom|Left|Right|NotSet" CellPadding="n" CellSpacing="n" DataSourceID="id" EmptyDataText="string" GridLines="Both|Horizontal|Vertical|None" PageSize="n" ShowFooter="False|True" ShowHeader="False|True" HeaderStyle-property="value"... RowStyle-property="value"... AlternatingRowStyle-property="value"... FooterStyle-property="value"... property="value"... PagerSettings-property="value"... PagerStyle-property="value"... />
A GridView presents information from a data source organized as a table of rows and columns. It binds to the data source through its DataSourceID property, giving the id assigned to the data source control. A default GridView automatically generates as many columns as there are data fields retrieved from a data source; it generates as many rows as there are records in the retrieved recordset. Server style properties can be applied to the table as a whole and to specified rows and columns.
Creating a GridView Display
It requires very little declarative code, and no scripting, to produce a basic GridView table. The following table presents selected information from the BooksDB.mdb database. It is produced with two simple ASP.NET controls.
<asp:AccessDataSource id="BookSource" Runat="Server" DataFile="../Databases/BooksDB.mdb" SelectCommand="SELECT BookID, BookTitle, BookAuthor, BookPrice FROM Books WHERE BookType = 'Graphics' ORDER BY BookID"/> <asp:GridView id="BookGrid" DataSourceID="BookSource" Runat="Server" />
As shown in the above code, an <asp:GridView> control is paired with an <asp:AccessDataSource> control to extract a recordset for display from an Access database. The GridView is bound to the data source through its DataSourceID property giving the id of the AccessDataSource. The GridView creates as many columns of data as there are fields extracted by the data source's SelectCommand property. Column headings are automatically taken the field names in the database. As you can see, very little coding effort is needed to produce a tabular listing of database information with a default GridView.
Styling a GridView
Styling of a GridView takes place through various server style properties applied to the table as a whole or to selected rows. Coding a style property by its name and value applies it to the table as a whole; prefixing the property with HeaderStyle-, RowStyle-, AlternatingRowStyle-, or FooterStyle- applies the style to the identified section of the table. In the following example, Caption, CaptionAlign, CellPadding, BorderStyle, BorderWidth, BackColor, and ForeColor style properties are applied to the table. Different colors and fonts are applied individually to the header row and to alternating detail rows.
<asp:AccessDataSource id="BookSource" Runat="Server" DataFile="../Databases/BooksDB.mdb" SelectCommand="SELECT BookID, BookTitle, BookPrice, BookAuthor FROM Books WHERE BookType='Graphics' ORDER BY BookID"/> <asp:GridView id="BookGrid" DataSourceID="BookSource" Runat="Server" Caption="<b>Table 1. Graphics Books</b>" CaptionAlign="Left" CellPadding="2" BorderStyle="Ridge" BorderWidth="5" BackColor="#F0F0F0" ForeColor="#000000" Font-Name="Verdana" Font-Size="10pt" HeaderStyle-BackColor="#707070" HeaderStyle-ForeColor="#FFFFFF" AlternatingRowStyle-ForeColor="#FFFFFF" AlternatingRowStyle-BackColor="#A0A0A0" />
In the above example, property settings for the GridView are listed on separate lines. This practice is followed for ease of reading the code. However, properties can be coded in-line and have the same effect. More compact coding of a GridView is shown below. This code produces the same output as in Figure 7-3.
<asp:GridView id="BookGrid" DataSourceID="BookSource" Runat="Server" Caption="<b>Table 1. Graphics Books</b>" CaptionAlign="Left" CellPadding= "2" BorderStyle="Ridge" BorderWidth="5" BackColor="#FFCCCC" ForeColor= "#330000" Font-Name="Verdana" Font-Size="10pt" HeaderStyle-BackColor= "#990000" HeaderStyle-ForeColor="#FFFFFF" AlternatingRowStyle-ForeColor= "#FFFFFF" AlternatingRowStyle-BackColor="#CC6666"/>
Selecting and Formatting Columns
Although the default GridView is a quick and easy way to display database information, you probably will want more control over its display. In the above example, all columns of data are left aligned and numbers are displayed in raw numeric formats. Preferably, numeric columns are right-aligned and displayed in currency formats. Also, column headings, which are taken from database field names, may not be as descriptive as preferred or styled to aesthetic preferences. In addition, you may wish to apply different stylings to selected columns rather than accept common row formatting across all columns.
For these and other purposes the GridView supplies a <Columns> section. Within this section, one or more <asp:BoundField> controls select and specify exactly how a column of information is presented. The general formats for a Columns section and its BoundField controls are shown in Figure 7-4.
<asp:GridView id="id" Runat="Server" AutoGenerateColumns="False" ShowFooter="False|True" ... > <Columns> <asp:BoundField DataField="field" DataFormatString="{string}" FooterText="string" HeaderText="string" HtmlEncode="False|True" NullDisplayText="string" SortExpression="field" HeaderStyle-property="value"... ItemStyle-property="value"... FooterStyle-property="value"... /> ... </Columns> </asp:GridView>
In order to use BoundFields rather than automatically generated columns, AutoGenerateColumns="False" must be specified for the GridView. Irrespective of the number of data fields returned by the data source's SelectCommand, only those fields identified in a BoundField control are displayed in the GridView. If you forget to turn off automatic columns, all fields from the data source are automatically displayed along with BoundField columns. You end up with duplicate columns.
Enclosed inside the <Columns> tag are one or more <asp:BoundField> controls identifying and formatting a field from the data source. The database field to bind to a BoundField is given in its DataField property. A BoundField's column heading is given by its HeaderText property to override use of the field name from the data source. A BoundField can display a footer row by assigning a text string to its FooterText property and making sure to specify ShowFooter="True" for the GridView to display this row. A footer row cannot display data bound from a data source.
If the data value for one of the rows of a BoundField is nullif a database field is emptya text string can be specified for display in place of an empty cell by coding the NullDisplayText attribute. A GridView permits sorting of records based on field values. The sort field for the column is given by the SortExpression property. GridView sorting is taken up in a later tutorial.
A BoundField column of data can have its own styling that is different from overall table and row styling. Style properties for a BoundField are prefixed with HeaderStyle-, ItemStyle-, and FooterStyle- to apply to these sections of the bound column. Note that "ItemStyle-" for a BoundField differs from "RowStyle-" used for the overall GridView.
Importantly, the data value displayed in a BoundField through its DataField property is encoded as a string before the format given by its DataFormatString property is applied. This means that numbers and dates will not take on the numeric or data/time formats given in the DataFormatString (strings cannot be formatted as numbers and dates). You can, however, prohibit this string conversion by setting HtmlEncode="False" for these types of BoundFields. Then, format strings such as "{0:C}" (currency), "{0:N}" (number), and "{0:D}" (long date) will be properly applied.
Use of BoundField columns in a GridView produces the output shown below. In this case, all data fields are selected from the database; however, only five of these fields are chosen and formatted as bound columns.
<asp:AccessDataSource id="BookSource" Runat="Server" DataFile="../Databases/BooksDB.mdb" SelectCommand="SELECT * FROM Books WHERE BookType='Graphics' ORDER BY BookID"/> <asp:GridView id="BookGrid" DataSourceID="BookSource" Runat="Server" AutoGenerateColumns="False" ShowFooter="True" Caption="<b>Graphics Books</b>" CellPadding="3" BorderStyle="Ridge" BorderWidth="5" BackColor="#F0F0F0" ForeColor="#000000" Font-Name="Verdana" Font-Size="10pt" HeaderStyle-BackColor="#707070" HeaderStyle-ForeColor="#FFFFFF" AlternatingRowStyle-ForeColor="#FFFFFF" AlternatingRowStyle-BackColor="#A0A0A0" FooterStyle-BackColor="#707070" FooterStyle-ForeColor="#FFFFFF" FooterStyle-Font-Size="7pt" > <Columns> <asp:BoundField DataField="BookID" HeaderText="ID" FooterStyle-BorderWidth="0"/> <asp:BoundField DataField="BookTitle" HeaderText="Title" FooterStyle-BorderWidth="0"/> <asp:BoundField DataField="BookAuthor" HeaderText="Author" FooterStyle-BorderWidth="0"/> <asp:BoundField DataField="BookPrice" HeaderText="Price" HtmlEncode="False" DataFormatString="{0:C}" ItemStyle-HorizontalAlign="Right" FooterStyle-BorderWidth="0"/> <asp:BoundField DataField="BookQty" HeaderText="Qty*" HtmlEncode="False" DataFormatString="{0:D}" ItemStyle-HorizontalAlign="Right" FooterText="*In stock" FooterStyle-BorderWidth="0"/> </Columns> </asp:GridView>
Note in the above code that the DataField property of a BoundField must match exactly a field name in the data source; its HeaderText, however, can be any heading string. Also, numeric fields are assigned HtmlEncode="False" in order for their DataFormatStrings to be properly applied as currency and integer formats.
In this example, the footer row is made visible to display a text string. The property ShowFooter="True" is coded in the GridView to display this row. The text contents of the footer is given by the FooterText property of the BoundField containing the text; FooterStyle- settings are also applied. Notice that there are no gridlines separating the columns in the footer row. Their display is suppressed with FooterStyle-BorderWidth="0" coded in all column footers.
At present, the GridView control is demonstrated for output displays. In later tutorials you will learn how to use this control for other database processing tasks such as updating database records with new information and deleting records from a database.