2.18. Formatting Columnar Data in a GridView


You need to format dates and numbers in your GridView controls.


Use the DataFormatString attribute of the asp:BoundField element:

  1. Within the .aspx file that contains the GridView control, add a BoundField element with the appropriate DataFormatString attribute for each column you want to format.

  2. If the DataFormatString does not provide the flexibility you need to format your data, use the ItemDataBound event instead to gain greater flexibility.

Figure 2-20 shows the appearance of an example GridView with the Publish Date and List Price columns formatted for dates and currency, respectively. Examples 2-48, 2-49 through 2-50 show the .aspx and code-behind files for an application that produces this result.

Formatting columnar data in a GridView output

Figure 2-20. Formatting columnar data in a GridView output


The formatting of dates and numbers in a GridView is performed with the DataFormatString attribute of the asp:BoundField element. The general format of the formatting string is {A:B}, where A is the zero-based index number of the property the format applies to (this is generally 0) and B specifies the format.

Numeric formats can be any of the following. Most numeric formats can be followed by an integer defining the number of decimal places displayed.

Table 2-2. 

Format character



Displays numeric values in currency format


Displays numeric ...

Get ASP.NET 2.0 Cookbook, 2nd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.