Monday, September 24, 2007

Data Formatting issues in GridView

You have a Grid bound to a datasource. You do all the right stuff by putting the correct formatting expressions in place for the BoundColumn. But when the page is rendered the columns are not formatted. I'm sure everybody would have encountered this at some point or the other while rendering data in ASP.NET 2.0 GridView.

The fix is straight, set the HtmlEncode property of the Bound Columns to "false". 

<asp:BoundField DataField="Number" DataFormatString="{0:c}"  HtmlEncode="false" HeaderText="Number" />
<asp:BoundField DataField="Date" DataFormatString="{0:MM/dd/yyyy}" HtmlEncode="false" HeaderText="Date" /> 

By default this property is set to True for security reasons. When the page is rendered, the output HTML is encoded to prevent cross site scripting (XSS) attacks. So make sure to turn off HtmlEncoding on those columns that you want to display formatted data.

No comments: