The DataGrid's BoundColumn control allows the data it displays to be formatted through the DataFormatString property.
The DataFormatString property is a string property, and should be assigned a value of the form: {0:Format}.
The formatting that can be applied to the DataSource field value being displayed by the BoundColumn depends upon the
type of the field. This FAQ examines how to provide formatting for numeric values. (For information on formatting date and time
values, be sure to check out the FAQ Formatting Date and Time Data.)
There are eight predefined numeric formatting specifies, summarized in the table below. For the Example column in the table below, the value used is 2003.0515, or 2003 for format providers that require integers.
| Format Pattern | Name | Example |
|---|---|---|
C or c | Currency format | $2,003.05 |
D or d | Decimal format (Works for integers only!) | 2,003 |
E or e | Scientific (exponential) format | 2.003052e+003 |
F or f | Fixed-point format | 2003.05 |
G or g | General format | 2003.0515 |
N or n | Number format | 2,003.05 |
P or p | Percent format | 2,00305.15% |
X or x | Hexadecimal format (Works with integers only!) | 7D3 |
So, if we have a DataSource field that is, say, a price for our product, we can format the price as a currency using
the following DataGrid declaration:
|
|
Notice that we can have the data displayed in a currency formatting by simply setting the DataFormatString to
{0:c}, or, in general, to {0:Format}.
| Formatting Depends Upon the Web Server's Culture Settings |
| The output for the various formats depends upon the Web server's Culture Settings. Through the Regional Settings in the Control Panel, you can specify how Numbers, Dates, and Currencies should be displayed. |
Formatting Non-Numeric Data as Numeric Data
Imagine that for some reason the data you want to format as, say, a currency, is not of a numeric datatype. That is, what if the
data is a string, but has as its contents just numbers? The {0:c} format specify won't display the string as a currency,
since it only formats numeric data into currency. The solution is to use a TemplateColumn, cast the string data to numeric data, and
then format it using the currency formatter.
To accomplish this, use the following DataGrid declaration:
|
|
| VB.NET |
The above code first uses Convert.ToInt32() to convert the string DataSource field ColumnName into
an integer. It then uses the String.Format() method to format the integer as a currency. Note that the above
code will throw a runtime exception if the dat in the ColumnName field cannot be cast to an integer. Therefore, only
use this method if you are certain that the data you will be getting from the DataSource field is indeed castable to a
numeric value.
Home | FAQs | Articles | About | Buy the Book!
Copyright 2006, Scott Mitchell. All Rights Reserved.