Monday, June 30, 2008

Formatting Date in the ASP.NET GridView

This GridView is bound to a DataTable that has a column of type DateTime:
I want to just see the date and not the time. So I set that column's DataFormatString to {0:MM/dd/yyyy}. Refresh the page and this is what you get:
Why didn't it change? It has to do with HTML Encoding. ASP.NET will get the date from the data store, html encode it, and THEN apply the formatting. By this time the string cannot be formatted anymore so you see it as unchanged.

So how do you fix this? Tell ASP.NET not to html encode your date time column. You do this through the column's properties: Refresh the page and it should come out ok:
More Info: MSDN: Formatting Dates in GridViews