Friday, June 1, 2007

Formatting a Column in a GridView with DataFormatString

Today I came across a little gotcha with the ASP.Net GridView control.
If you have a bound column bound to a DateTime field and you want to change the formatting say from "05/30/2007 15:25:22" to "05/30/2007" then the way to do this is to use the DataFormatString parameter of the BoundField:


<asp:BoundField datafield="EVENT_DATE" headertext="Event Date" DataFormatString="{0:MM/dd/yyyy}">
<ItemStyle width="10%"></ItemStyle>
</asp:BoundField>



But this didn't seem to work for some reason. The fix is to switch off HTML encoding for the column, as explained in this Microsoft post.

So the correct code is:

<asp:BoundField datafield="EVENT_DATE" headertext="Event Date" DataFormatString="{0:MM/dd/yyyy}" HtmlEncode="False">
<ItemStyle width="10%"></ItemStyle>
</asp:BoundField>



Now it works like a charm ...