Formatting bound ASP.NET types requires explicitly changing the HtmlEncode property
I ran into this one while migrating our Beta 2 code to VS RTM for an internal reporting site, but the behavior for ASP.NET 2.0 changed within betas and, in short, anytime you want to add a formatting string, like any of the numeric or date format strings in a bound field , you have to explicitly set the HTMLEncode property to "false".
Here's what your code should look like with the newly added property in bold.
<asp:BoundField DataField="Total" DataFormatString="{0:#,###}" HtmlEncode ="False" />
Before HtmlEncode property | After HtmlEncode property |
Total100000000 | Total100,000,000 |
Why does ASP.NET need the explicit HtmlEncode property? From an internal thread, the short answer is that ASP.NET will by default assume the value is html encoded and then treat it like a string which rules out numeric/date formatting.
Comments
Anonymous
February 08, 2006
I've experienced the same thing. It makes no sense, since the format string doesn't include any characters that is being htmlencoded. However, if you change your formatstring to {0:N} it will work without htmlencode=false.
----------------------------------------------------
www.madskristensen.dkAnonymous
February 08, 2006
That's worth knowing...
Um, I know this isn't the right place, but could I make a suggestion for an enhancement?
Since it doesn't seem reasonable that someone would every explicitly set a format string that they wanted to be ignored, would it be possible to make setting a format string attribute automatically cause an HtmlEncode attribute with value "False" to be added?
Or at least have that behaviour available as a configurable option?Anonymous
February 08, 2006
I think that qualifies as a bug. Or a dumb design flaw. The HtmlEncode should be applied AFTER the DataFormatString. This behavior is just silly and really confusing.Anonymous
February 08, 2006
Also, {0:N} with HtmlEncode off doesn't work for me (Reflector seems to agree on that ;-) At least it's consistent. But unless I'd read your blog, it would have been a loooong search to find the cause of DataFormatString not working. Thanks!
Overriding BoundField.FormatDataValue would be an option, as it's virtual. Hmmm...Anonymous
January 11, 2007
The comment has been removedAnonymous
October 31, 2007
在GridView中如何格式化Money型字段(downmoon)?Anonymous
December 29, 2007
在GridView中如何格式化Money型字段(downmoon)?Anonymous
January 28, 2008
I hit this as well, seems pretty silly. thanks for the info!Anonymous
March 14, 2008
This is no longer true. It displays the formatting whether you set it to false or true, but on some workstations it may still show the formatting to be absent. Upload it to the Web and it'll work just fine. I think it's something that got patched in a framework or VS update.Anonymous
April 14, 2009
收集一些在DataGridVeiw使用技巧,备用。 一、DataGridView单元格验证 1、定义单元格验证要求:验证错误后焦点不离开。实现:单元格的验证可以使用dgv_details_Cel...