Formatting data in databound controls

Posted by andy gaskell on Apr 18th, 2006

I’ve been trying to format DateTime and currency in asp.net 2.0 databound controls (DetailsView and GridView). After some googling I was able to get it figured out.

To format DateTime values, you might expect to use a tag like this:

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

and have a result like this:
10/10/2004

but instead you get a result like this:
10/10/2004 12:00:00 AM

Here’s the fix – add HtmlEncode=”false” to your BoundField tag:

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

The same idea applies to formatting currency, I’m assuming other types of data formatting as well. Here’s Microsoft’s explanation.

Technorati Tags: , , , ,

One Response

  1. Joe Thompson Says:

    whoever you are, you are a genius!

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.