Monday, November 12, 2007

Formatting bounded DateTime fields in ASP.NET

If you ever tried to work with BoundField object bound to a DateTime field with the DataFormatString, it must happen, that first time you didn't get your DateTime value proeprly formatted.
<asp:BoundField DataField="MyNotFormattedDate" DataFormatString="{0:MM/dd/yyyy}" />

Looks like that you have done everything correct but still getting your value formatted using its ToString() method like "11/13/2007 10:05:12 PM". So, the problem is not in your definition but in ASP.NET which tries to prevent cross site scripting attacks, the field value is HTMLEncoded. And HTMLEncoding occurs before applying any formatting, making your formatting string without effects. To Get your field formatted as you define, you should tell object not to use HTMLEncoding like

<asp:BoundField DataField="MyFormattedDate" DataFormatString="{0:MM/dd/yyyy}" HtmlEncode="false"/>

Compare databases with the best tool - DBTYP.NET Studio.

No comments: