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 date and time values. (For information on formatting numeric
fields, be sure to check out Formatting Numeric Data.)
There are eight predefined date and time formatting specifies, summarized in the table below. For the Example column in the table below, the value used is August 27, 1989, with a time of 3:32:00 PM. (This table is taken directly from my latest book, Teach Yourself ASP.NET in 24 Hours, Complete Starter Kit. Note that the output for these is from my own computer, which is for the English, U.S. Culture Setting and which is located seven hours from Greenwich Mean Time.)
| Format Pattern | Name | Example |
|---|---|---|
d | Short date format | 8/27/1989 |
D | Long date format | Sunday, August 27, 1989 |
t | Short time format | 3:32 PM |
T | Long time format | 3:32:00 PM |
f | Full date/time format (short time) | Sunday, August 27, 1989 3:32 PM |
f | Full date/time format (long time) | Sunday, August 27, 1989 3:32:00 PM |
g | General date/time format (short time) | 8/27/1989 3:32 PM |
G | General date/time format (long time) | 8/27/1989 3:32:00 PM |
m or M | Month day format | August 27 |
r or R | RFC 1123 format | Sun, 27 Aug 1989 8:32:00 GMT |
s | Sortable date/time format | 1989-08-27T15:32:00 |
u | Universable sortable date/time format | 1989-08-27 15:32:00z |
U | Universable sortable date/time format | Sunday, August 27, 1989 11:32:00 PM |
y or Y | Year month format | August, 1989 |
So, if we have a DataSource field that is a date/time field we can format the field as a just a date (without the time)
using the following DataGrid declaration:
|
|
Formatting Non-Date/Time Data as Date/Time Data
Imagine that for some reason the data you want to format as, say, just the date less the time, is not of a date/time datatype. That
is, what if the data is a string, but has as its contents a valid date/time? The {0:d} format specify won't display the
string as just the date, since it only formats date/time data into just the date. The solution is to use a TemplateColumn, cast the string
data to date/time data, and then format it.
To accomplish this, use the following DataGrid declaration:
|
|
| VB.NET |
The above code first uses Convert.ToDateTime() to convert the string DataSource field ColumnName into
a date/time value. It then uses the String.Format() method to format the date/time as just the date. Note that the above
code will throw a runtime exception if the dat in the ColumnName field cannot be cast to a date/time.
Home | FAQs | Articles | About | Buy the Book!
Copyright 2006, Scott Mitchell. All Rights Reserved.