DataFormatString doesn't seem to work on BoundField elements

I was using the BoundField element in ASP.NET 2.0’s GridView control. More specifically, I was attempting to use the DataFormatString element in order to change the look of dates and dollar amounts as they get displayed. Much to my dismay, it didn’t look like the format string was being applied to the data.

After digging around a bit (and making sure that my memory of the format codes was accurate), it turns out that the problem is caused by a combination of factors. The first is that the default value for the HtmlEncode is true. The HtmlEncode property determines whether the value of the bound field is HTML encoded before being transmitted to the browser. The second factor is that, when the DataFormatString is applied to the value, any HTML encoding takes place prior to the formatting.

When, for example, a date is rendered, the date value is converted to string using the ToString() method. The string is then HtmlEncoded. Finally, the String.Format method is used to format the string using your format codes. However, your date format codes won’t work because the ‘date’ is no longer a DateTime variable. It’s a string. So instead of formatting the data, it is displayed using the ToString() layout. The same problem exists for other non-string types, including currency, floats, etc.

The solution is to set the HtmlEncode attribute to false on the BoundField element. Now the value is not converted to a string prior to the Sting.Format method call, the result being that the String.Format method uses the typed value (not the ToString version) and the format string in the manner that you (and I) expect.