To read the article online, visit

ASP.NET Data Web Controls Kick Start
Chapter 3: Customizing the HTML Output
By Scott Mitchell

Specifying Column-Level Display Properties

As we've seen in previous chapters, the DataGrid control, by default, creates an HTML table with as many rows and columns as there are in the DataSource. However, by setting the AutoGenerateColumns property to False, you can explicitly specify what fields from the DataSource should be included in the DataGrid. Recall that to add a column to the DataGrid you must add an appropriate control in the DataGrid's Columns tag. That is, using our authors example, a DataGrid that had columns for the author's first and last name might look like this:

<asp:DataGrid runat="server" id="dgAuthorsNames">
 <asp:BoundColumn DataField="au_fname" HeaderText="First Name" />
 <asp:BoundColumn DataField="au_lname" HeaderText="Last Name" />

Recall that the following controls can be used within the Columns tag:

  • BoundColumn

  • TemplateColumn

  • EditColumn

  • ButtonColumn

  • HyperLinkColumn

Not surprisingly, you can specify various display properties for each of these column controls. In this chapter, we'll look at customizing the stylistic properties for the BoundColumn and TemplateColumn controls. For now we'll omit examination of EditColumn, ButtonColumn, and HyperLinkColumn, because we'll be seeing much more of these controls in later chapters.

Specifying Display Properties for the BoundColumn Control

The BoundColumn control contains three "ItemStyle" properties: ItemStyle, HeaderStyle, and FooterStyle. These "ItemStyle" properties indicate style information for the particular column. They contain the same set of display properties as the "ItemStyle" properties examined in the previous section.

In addition to these "ItemStyle" properties, the BoundColumn control contains a few other display properties. One we've seen in past examples is the HeaderText property, which specifies the text that should appear in the header of the column. This is useful if your DataSource has obscure field names (such as au_lname). A FooterText property is also included. The BoundColumn control also contains a HeaderImageUrl property, which, if specified, will place an img tag in the header.

The final display property for the BoundColumn control is the DataFormatString property. This string property specifies how the data in the column should be formatted. The syntax for the format string is a bit strange at first glance: {0:formatString}. This is the same syntax used for the String.Format() method, which we saw in a code example at the end of Chapter 2.

The String.Format() method accepts a string as its first parameter, and then accepts a variable number of parameters of type Object. The string parameter is a format string, which can contain a mix of normal text and format placeholders. The objects are the variables whose values we want to have plugged into the formatting placeholders.

For example, imagine that we have two variables of type float in C#, or of type Single in Visual Basic .NET, called basePrice and salesTax. The basePrice variable contains the sum of the prices for the products ordered by our customer, whereas the salesTax price is the sales tax on the customer's purchase; hence the total price due is the sum of these two variables.

Now, it would be nice to display a message indicating the customer's total, and how it was derived. We might want to have an output like: "Your total comes to $6.50. The base price was $5.75 and the sales tax was $0.75." To accomplish this, we could use the String.Format method like so:

String s = String.Empty;
String strFormat = "Your total comes to {0:c}. The base price was {1:c} " +
     "and the sales tax was {2:c}.";
s = String.Format(strFormat, basePrice+salesTax, basePrice, salesTax)

Note that the formatting placeholders ({0:c}, {1:c}, and {2:c}) indicate two things: the ordinal ranking of the variable whose value should be used when applying the formatting information, and the formatting to use. That is, {0:c} will apply a currency formatting to the 0th parameter (basePrice+salesTax)—note that c represents a currency formatting. {1:c} will apply a currency formatting to the 1st parameter, basePrice (really the 2nd one, because we start counting at 0). Finally, {2:c} will apply a currency formatting to the 2nd parameter, salesTax.

The DataStringFormat property of the BoundColumn control works in a similar fashion: Here you must specify the formatting placeholder. Keep in mind that the value that is inserted into the cell from the DataSource is the 0th parameter. Hence, if you have a field that stores, say, the price of each product, you can have it displayed as a currency by setting the BoundColumn control's DataFormatString to {0:c}. That is, the DataGrid might look like this:

<asp:DataGrid runat="server" id="dgAuthorsNames">
 <asp:BoundColumn DataField="Name" HeaderText="Product Name" />
 <asp:BoundColumn DataField="Price" HeaderText="Price"
      DataFormatString="{0:c}" />

Clearly the c format string formats the specified variable value as a currency, but what other format strings are available? Table 3.3 lists a few of the more common ones, but there are far too many possibilities to list here. Instead, check out Microsoft's Formatting Overview page at

Table 3.3 Common Formatting Strings

Formatting String



Displays numeric values in currency format


Displays numeric values in decimal format and date/time variables in a short date pattern


Displays numeric values in hexadecimal format

Listing 3.3 illustrates setting a number of display properties for the BoundColumn controls. The source code is omitted from the listing, but it is the same as the source code from Listing 3.1, except that the SQL query on line 11 has been changed from SELECT * FROM authors to SELECT * FROM titles. Hence, the code in Listing 3.3 presents information about the various books in the database.

Listing 3.3 Column-Level Display Properties Can Be Set via the BoundColumn Control

 1: <asp:datagrid id="dgTitles" runat="server"
 2:  AutoGenerateColumns="False"
 3:  Font-Name="Verdana" Width="50%"
 4:  HorizontalAlign="Center" ItemStyle-Font-Size="9">
 6: <HeaderStyle BackColor="Navy" ForeColor="White"
 7:   HorizontalAlign="Center" Font-Bold="True" />
 9: <AlternatingItemStyle BackColor="#dddddd" />
11: <Columns>
12:  <asp:BoundColumn DataField="title" HeaderText="Title"
13:      ItemStyle-Width="70%" />
15:  <asp:BoundColumn DataField="price" HeaderText="Price"
16:      DataFormatString="{0:c}"
17:      ItemStyle-HorizontalAlign="Right"
18:      ItemStyle-Width="15%" />
20:  <asp:BoundColumn DataField="ytd_sales" HeaderText="Sales"
21:      DataFormatString="{0:#,###}"
22:      ItemStyle-HorizontalAlign="Right"
23:      ItemStyle-Width="15%" />
24: </Columns>
25: </asp:datagrid>

In Listing 3.3, there are three BoundColumns presenting key information from the titles table in the pubs database. The first BoundColumn (lines 12 and 13) simply shows the book's title. On line 13, the Width of the column is set to 70% via the ItemStyle property. Because we are working with column-level display properties, this width setting is relative to the table width, meaning the first column will be 70% of the total width of the table. Note that in line 3 we specified that the table should have a Width of 50% (this is relative to the Web page).

The second BoundColumn (lines 15–18) displays the price of the book. Line 16 sets the DataFormatString so that the value will be formatted as a currency. On line 17, the column values are specified to be right-aligned, and on line 18, the Width of the column is set to 15% (of the total width of the table).

The last BoundColumn (lines 20–23) displays the year-to-date sales. The DataFormatString on line 21 indicates that there should be a comma separating each of the three digits. The HorizontalAlign and Width properties on lines 22 and 23 mirror those on lines 17 and 18.

Figure 3.3 shows a screenshot of Listing 3.3 when viewed through a browser.

Figure 3.3
Each column has specific stylistic properties set, such as formatting and alignment.

Specifying Display Properties for the TemplateColumn

Recall that the DataGrid can employ templates through the use of the TemplateColumn control. This control applies a template to a specific column in the DataGrid, as shown in the following code snippet:

<asp:DataGrid runat="server" id="dgTemplateColumnExample">
  <%# DataBinder.Eval(Container.DataItem, "SomeColumnName") %>

The display properties of the TemplateColumn are a subset of those of the BoundColumn. Specifically, the TemplateColumn's display properties include the following:

  • HeaderText

  • HeaderImageUrl

  • FooterText

  • ItemStyle

  • HeaderStyle

  • FooterStyle

With the TemplateColumn, you have more control over the display in the header and footer through the use of the HeaderTemplate and FooterTemplate.

Let's look at some code. Listing 3.4 contains a DataGrid that uses the same source code as Listing 3.3—it populates a SqlDataReader with the query SELECT * FROM titles and binds it to the DataGrid dgTitles. As with Listing 3.3, the source code has been removed from Listing 3.4 for brevity.

In Listing 3.4, a DataGrid with a BoundColumn control and a TemplateColumn control is created. The BoundColumn control displays the title of the book, and the TemplateColumn control displays information on the book's sales performance—essentially a simple sentence noting how many copies have been sold at what price. Three of the TemplateColumn control's display properties—HeaderText (line 15), and two ItemStyle properties (HorizontalAlign and Wrap on lines 16 and 17, respectively)—have been set declaratively.

Listing 3.4 The TemplateColumn Control Contains Display Properties Nearly Identical to That of the BoundColumn Control

 1: <asp:datagrid id="dgTitles" runat="server"
 2:  AutoGenerateColumns="False"
 3:  Font-Name="Verdana" Width="50%"
 4:  HorizontalAlign="Center" ItemStyle-Font-Size="9">
 6: <HeaderStyle BackColor="Navy" ForeColor="White"
 7:   HorizontalAlign="Center" Font-Bold="True" />
 9: <AlternatingItemStyle BackColor="#dddddd" />
11: <Columns>
12:  <asp:BoundColumn DataField="title" HeaderText="Title"
13:      ItemStyle-Width="70%" />
15:  <asp:TemplateColumn HeaderText="Sales Performance"
16:   ItemStyle-HorizontalAlign="Right"
17:   ItemStyle-Wrap="False">
18:  <ItemTemplate>
19:   <b><%# DataBinder.Eval(Container.DataItem, "ytd_sales", "{0:#,###}") %></b>
20:   copies sold at
21:   <b><%# DataBinder.Eval(Container.DataItem, "price", "{0:c}") %></b>
22:  </ItemTemplate>
23:  </asp:TemplateColumn>
24: </Columns>
25: </asp:datagrid>

Notice that we set the ItemStyle.Wrap property to False on line 17. This means that the text in this column will not wrap. Because the overall table width is defined to be 50% of the page (see the Width property on line 3), if we shrink the browser or lower the monitor resolution, the second column's text will remain all on one line, and the Title column's text will start wrapping.

Also notice that the DataBinder.Eval() method call on lines 19 and 21 uses three parameters instead of the two we've seen thus far. The third parameter specifies a format string (which follows the same guidelines and rules as the format string in the String.Format() method or the BoundColumn control's DataFormatString property. Hence, on lines 19 and 21 the value of the ytd_sales and price fields are formatted as currency (recall that the c applies a currency format).

Figure 3.4 shows a screenshot of the code in Listing 3.4 when viewed through a browser. Note that the rows that have NULLs for price and ytd_sales (The Psychology of Computer Cooking and Net Etiquette) are missing the numeric values for the sales number and sales price, but still have the string "copies sold at" present. Ideally, we don't want this string to display fields that have NULL values for these two database fields; perhaps we'd like to have a message like "Currently no copies of this book have been sold" appear instead. We'll see how to accomplish this later in this chapter, in the section "Customizing Data-Binding Output in Templates."

Figure 3.4
A TemplateColumn is used to display the sales and price for each book.

  • Read Part 4

  • Article Information
    Article Title: ASP.NET Data Web Controls Kick Start Sample Chapter
    Article Author: Scott Mitchell
    Published Date: Thursday, February 27, 2003
    Article URL:

    Copyright 2017 QuinStreet Inc. All Rights Reserved.
    Legal Notices, Licensing, Permissions, Privacy Policy.
    Advertise | Newsletters | E-mail Offers