BoundField DataFormatString attribute not being applied.

Version: ASP.net 2.0 RTM

I wasted a few minutes figuring out this one.

You have a BoundField object in a GridView bound to a field of type DateTime with a DataFormatString attribute but the format string is not being applied.

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

Instead, the field appears to be formatted using its ToString() method like so:
Output: 10/31/2005 7:00:54 PM
 

Cause

To prevent cross site scripting attacks, the field value is HtmlEncoded. The HtmlEncoding occurs before applying the DataFormatString making the format string have no effect.

 

Resolution

In this case (ie. when using a field of type DateTime), set HtmlEncode to false.

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

The Output renders as: 10/31/2005

This setting also applies to the HeaderText.
The following:
HeaderText="Employee<BR/>Name"
will not render a line break unless you set HtmlEncode to false.


I am not sure why the ASP.net team decided against HtmlEncoding the string after applying the DataFormatString.

Update for 3.5 SP1, 3.0 SP1, 2.0 SP1
SP1 introduces a new property called HtmlEncodeFormatString which allows you to specify whether the formatted text should be HTML encoded when it is displayed.

86 Comments

Comments have been disabled for this content.