C# VB.Net Formatting Number Numeric Field with Decimal Places in GridView in Asp.Net

In my previous article i have explained “C# VB.Net Formatting DateTime Field in GridView in Asp.Net“. In this article i will explain How to Format Number or Numeric Data in a GridView using C# & VB.Net. I will also discuss with Currency datatype & will show show example code from both Design time & Run time/Code behind aspect. So lets start to Format your GridView as per your number format.

List of Numeric Formats for GridView Row or Column:

Format Description Example
C Currency format $10.00
D Decimal format 10
E Scientific format 1.000000E+001
F Fixed format 10.00
G General format 10
N Number format 10.00
X Hexadecimal format A

Note: Format characters are not case-sensitive, except for “X”. The value after the format character specifies the number of significant digits or decimal places to display. For example, the formatting string “{0:F2}” displays a fixed-point number with two decimal places.

Format Numeric/Number Data in GridView Bound Column:

<asp:BoundField DataField="Price" HeaderText="Price" DataFormatString="{0:C2}" HtmlEncode="false">

Note: Don’t forget to add HtmlEncode=”false”. I will discuss later.

Formatting Number for GridView Column Data from Code behind:
To format GridView data from run time or from code behind you can use GridView RowDataBound method like below:
C# Code:

    protected void gvEdit_RowDataBound(object sender, GridViewRowEventArgs e)
        if (e.Row.RowType == DataControlRowType.DataRow)
            ((Label)e.Row.FindControl("lbl")).Text = Convert.ToDecimal(((DataRowView)e.Row.DataItem)["Price"]).ToString("C5");

VB.Net Code:

    Protected Sub GridView1_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs)
        If e.Row.RowType = DataControlRowType.DataRow Then
            CType(e.Row.FindControl("lbl"), Label).Text = Convert.ToDecimal(CType(e.Row.DataItem, DataRowView)("Price")).ToString("C5")
        End If
    End Sub


Note: You may need to add few prefix like AU/US then use :
DataFormatString=”AU {0:C5}” HtmlEncode=”false”
DataFormatString=”US {0:C5}” HtmlEncode=”false”

What is HtmlEncode?
Microsoft introduced this new property to prevent cross site scripting (CSS) attacks. This way if there is any malicious text in the fields, it will get encoded and will not execute on client’s browser. If this property is set to true, the formatting implementation in the control first encoded the text using HttpUtility.HtmlEncode. And after that it calls String.Format method on the encoded text value. Where as when HtmlCode is set to false, the formatting is done on the data value itself. So the way to fix your problem with formatting would be to set HtmlEncode property to false.

Posted in .Net, Asp.net, C#, Gridview, VB.Net

Leave a Reply

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