Each BoundField column in GridView provides a DataFormatString property you can use to configure the appearance of numbers and dates using a format string.
Format strings generally consist of a placeholder and a format indicator, which are wrapped inside curly brackets. A typical format string looks something like this:
{0:C}
In this case, the 0 represents the value that will be formatted, and the letter indicates a predetermined format style. Here, C means currency format, which formats a number as an amount of money (so 3400.34 becomes $3,400.34). Here’s a column that uses this format string:
<asp:BoundField DataField="UnitPrice" HeaderText="Price"
DataFormatString="{0:C}" />
Below listing shows some of the other formatting options for numeric values.
Type - Currency
Format String - {0:C}
Example - $1,234.50. Brackets indicate negative values:($1,234.50). The currency sign is locale-specific.
Type - Scientific (Exponential)
Format String - {0:E}
Example - 1.234.50E+004
Type - Percentage
Format String - {0:P}
Example - 45.6%
Type - Fixed Decimal
Format String - {0:F?}
Example - Depends on the number of decimal places you set. {0:F3} would be 123.400. {0:F0} would be 123.
You can find other examples in the MSDN Help. For date or time values, you’ll find an extensive list. For example, if you want to write the BirthDate value in the format month/day/year (as in 12/30/08), you use the following column:
<asp:BoundField DataField="BirthDate" HeaderText="Birth Date"
DataFormatString="{0:MM/dd/yy}" />
Type - Short Date
Format String - {0:d}
Syntax - M/d/yyyy
Example - 10/30/2008
Type - Long Date
Format String - {0:D}
Syntax - dddd, MMMM dd,yyyy
Example - Monday, January 30,2008
Type - Long Date and Short Time
Format String - {0:f }
Syntax - dddd, MMMM dd,yyyy HH:mm aa
Example - Monday, January 30, 2008 10:00 AM
Type - Long Date and Long Time
Format String - {0:F}
Syntax - dddd, MMMM dd,yyyy HH:mm:ss aa
Example - Monday, January 30 2008 10:00:23 AM
Type - ISO Sortable Standard
Format String - {0:s}
Syntax - yyyy-MM-ddTHH:mm:ss
Example - 2008-01-30T10:00:23
Type - Month and Day
Format String - {0:M}
Syntax - MMMM dd
Example - January 30
Type - General
Format String - {0:G}
Syntax - M/d/yyyy HH:mm:ss aa (depends on locale- 10:00:23 AM
specific settings)
Example - 10/30/2008
The format characters are not specific to the GridView. You can use them with other controls, with data-bound expressions in templates (as you’ll see later in the “Using GridView Templates” section), and as parameters for many methods. For example, the Decimal and DateTime types expose their own ToString() methods that accept a format string, allowing you to format values manually.
No comments:
Write comments