First time here? You are looking at the most recent posts. You may also want to check out older archives or the tag cloud. Please leave a comment, ask a question and consider subscribing to the latest posts via RSS. Thank you for visiting! (hide this)
<asp:BoundField DataField="data"
      HeaderText="Data" SortExpression="data"
     DataFormatString="{0:d}" />

Why does this line of code (ehm... markup) always render the string "27/03/2007 0.00.00" as if it was just using a normal ToString(), instead of "27/03/2007", which is the result of the String.Format method using {0:d} (ShortDate format)?

At first I was thinking about some kind of error in the format string, but after carefully reading my format string bible I decided it was not my fault: a few search on Google and I found out this interesting post about some breaking changes in the ASP.NET 2.0 GridView.

The ASP.NET team decided to HtmlEncode by default all texts in order to prevent possible Cross-Site Scripting attacks. And for some strange reasons the HtmlEncode is applied before the Format method: to use the Format string now you need to add a HtmlEncode="false".

So, the correct definition for the bound field should be that one:

<asp:BoundField DataField="data"
 HeaderText="Data" SortExpression="data"
 DataFormatString="{0:d}" HtmlEncode="false" />

And the same applies to column headers: if you write HeaderText="Start<br>Date" and you don't say not to HtmlEncode it, then you will not see the 2 lines.

Bug or feature? This is the question...

posted on Tuesday, March 27, 2007 1:10 AM

Comments on this entry:

# re: DataFormatString is not applied to BoundField

Left by Steve Harman at 3/27/2007 1:52 AM

I actually ran into this very issue last week - and IMHO this is a bug. I understand where the asp.net team was coming from when they decided to HtmlEncode by default - but I don't see why you would HtmlEncode prior to applying any format strings.

# Re: DataFormatString is not applied to BoundField

Left by Michele Bersani at 3/27/2007 11:12 PM

There is also my tip on UGIdotNEt about that ;-)
http://www.ugidotnet.org/tips/tips_read.aspx?ID=164

# re: DataFormatString is not applied to BoundField

Left by Canz at 10/1/2007 4:49 PM

well done!!! tnx for your help

Comments have been closed on this topic.