2.18. Formatting Columnar Data in a GridView
Problem
You need to format dates and numbers in your GridView
controls.
Solution
Use the DataFormatString
attribute of the asp:BoundField
element:
Within the .aspx file that contains the
GridView
control, add aBoundField
element with the appropriateDataFormatString
attribute for each column you want to format.If the
DataFormatString
does not provide the flexibility you need to format your data, use theItemDataBound
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.
Figure 2-20. Formatting columnar data in a GridView output
Discussion
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 |
Description |
---|---|
|
Displays numeric values in currency format |
|
Displays numeric ... |
Get ASP.NET 2.0 Cookbook, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.