ASP.NET – How to format Currency in GridView





Most sources tell you that formating a column in a GridView is simple, all you need to do is use the DataFormatString Property like so:

<asp:boundcolumn datafield=”Amount” headertext=”Amount” dataformatstring=”{0:c}”>

However you may find that the currency format is not working in the GridView, this is because the GridView’s columns are being Html Encoded.

A simple solution is to set the HtmlEncode property of the column to False.

Html encoding is a useful tool in several scenarios, recently I discovered how Html Encoding data to the response stream is able to stop cross site scripting attacks, but in this case where its your own GridView I don’t see any issues with turning the HtmlEncoding off.

Happy coding
Author: Robert Bertora




Tags: , , , , ,

2 Responses to “ASP.NET – How to format Currency in GridView”

  1. Naveed says:

    Cross site scripting attacks can be made only via input fields only. Therefore HtmlEncoding applies there i guess.

  2. Robert Bertora says:

    Yes I agree Naveed, a cross site scripting attack is usually instigated via input box. Though the attack itself only happens when the input field is rendered back out to the browser in a label text for example. So if for what ever reason some cross site scripting code makes it into your database, or your database is imported from CD or custom import process where you do not fully verify the source, you can still suffer the a possible scripting attack! In this scenario you should be reasonably safe that your currency field is genuine and has not been corrupted, so its safe to turn off the HtmlEncode as we both agree.