Monday, January 7, 2008

Formatting a Date in a GridView

How do I format a column in a GridView to just display the date or time of a DateTime object?

This is one of those things that should just work, but doesn't and can be very frustrating. If you have a Date or Time column in a GridView that displays data of type DateTime from a database you want to format the column to display either a date, or time, but not both. To do this, you would set the DataFormatString property of the column to the format of your choice as so:

<asp:BoundField DataField="Date" HeaderText="Date" SortExpression="Date" DataFormatString="{0:d}" />

<asp:BoundField DataField="Time" HeaderText="Time" SortExpression="Time" DataFormatString="{0:t}" />

However, after setting this property nothing happens. The GridView still displays the full DateTime and no formatting is displayed. Why? Because you need to set the HtmlEncode property for each of the columns to false. See below:

<asp:BoundField DataField="Date" HeaderText="Date" SortExpression="Date" DataFormatString="{0:d}" HtmlEncode="false" />

<asp:BoundField DataField="Time" HeaderText="Time" SortExpression="Time" DataFormatString="{0:t}" HtmlEncode="false" />



Anonymous said...

Not worked

Anonymous said...

thanks a lot i was driving crazy