ASP.NET DataFormatString and HtmlEncode

This seems to be one of those issues that keeps on confusing people and not surprisingly really.
When you set the DataFormatString on a bound field to something, say “{0:N2}” for a numeric field it seems the data is ignored. One way of fixing this is by selecting the “” link and turning the item into a template. There is however a better way and that is setting the HtmlEncode flag to false. This is actually caused because the value is Html encoded before the data formatting is done, I presume because of security reasons.

One thought on “ASP.NET DataFormatString and HtmlEncode

  1. Hi,

    as you correctly states, this is because of security reasons. HtmlEncode makes sure (at least in some manners) that XSS-attacks are not possible. HtmlEncode should always be on.

    In my opinion, a better solution is to use a templatefield and perform the formatting in code behind.

    I would also recommend Microsofts quite new AntiXss library. Its free, and uses a whitelisting-approach.

Leave a Reply

Your email address will not be published. Required fields are marked *