DataFormatString property on ASP.NET BoundField Ignored for Dates

Today one of my Iraqi devs, E, was trying to display some search results from a MySQL database in an ASP.NET GridView control. He simply set the DataSource property to the DataReader attached to the results, and called DataBind() on the grid control.

All was well, except the dates; they displayed in the short date/time format, even though the times are not used in this application (and thus were all 12AM). I showed him the beauty of the DataFormatString on the BoundField which displayed the date, but to my surprise, setting it to {0:d} didn’t change the output at all.

I scratched my head for a while, then came across MSDN Labs Bug ID FDBK35199, which describes the logic behind this intentional behavior. The reasoning? To prevent script injection attacks, the DataFormatString property is applied AFTER the value is HTML encoded, so it’s no longer a DateTime by the time it is formatted.

That’s fine, except the underlying value is a DateTime! No string representation of DateTime contains script elements, let alone malicious Javascript! So why, then, is this functionality so braindead!? Whatever happened to the principle of least surprise?!

Anyway, the fix is to disable HTML encoding by setting HtmlEncode to false on the BoundField element that displays date values. Lame!

Tags: , , , ,

Leave a Reply