Click here to Skip to main content
15,883,773 members
Articles / Web Development / ASP.NET
Tip/Trick

Data formatting in GridView

Rate me:
Please Sign up or sign in to vote.
3.00/5 (3 votes)
19 Nov 2009CPOL2 min read 32.9K   3   1
This article will discuss how you can format data that is displayed in grid view rows. A lot of time the data we get from data source is not exactly the way we want to render it. For example money values are stored as decimal values and we want to display the currency symbol when the values get rend

This article will discuss how you can format data that is displayed in grid view rows. A lot of time the data we get from data source is not exactly the way we want to render it. For example money values are stored as decimal values and we want to display the currency symbol when the values get rendered. Other case could be that you only want to display date in short format and not the full format with time values. This article will help in answering lot of those questions and will also discuss the problem we all ran into with HtmlEncode property of BoundField columns.

  • How to format data in GridView?
  • How to use DataFormatString property to format column values?
  • BoundField columns formatting does not work when DataFormatString property is specified.

Lets first see how you can specify the format string for the column. It is as simple as specifying DataFormatString property of the column. The following code snippet shows how DataFormatString value has been set on 2 columns to format them as currency and date fields.

<asp:GridView ID="ctlGridView" runat="server" autogeneratecolumns=False gridlines=Horizontal>
    <columns>
        <asp:boundfield datafield="ProductID" sortexpression="ProductID" />
        <asp:boundfield datafield="Name" headertext="Name" sortexpression="Name" />
        <asp:boundfield datafield="ProductNumber" headertext="Product Number" />
        <asp:BoundField DataField="ListPrice" HeaderText="List Price" DataFormatString="{0:c}" />
        <asp:BoundField DataField="SellStartDate" HeaderText="Sell Start Date" DataFormatString="{0:d}" />
    </columns>
</asp:GridView>							

Now you launch the page and your data formatting is not working. You did what was required to format the values. Almost all of us has run into this issue. There is another property HtmlEncode that is affecting this behavior. Bt default this property is set to true.

BoundField.HtmlEncodeEffect

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. It seems that this new property has made more people angry than making people happy. This is what this property is doing. 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. I will demonstrate this in action with following code.

private String FormatWithHtmlEncode()
{
    decimal dVal = 21345.00M;
    String strEnc = HttpUtility.HtmlEncode(dVal.ToString());
    System.Diagnostics.Debug.WriteLine(dVal.ToString());
    System.Diagnostics.Debug.WriteLine(strEnc);
    String strFormatted = String.Format(System.Globalization.CultureInfo.CurrentCulture, "{0:c}", new object[] { strEnc });
    System.Diagnostics.Debug.WriteLine(strFormatted);
    return strFormatted;
}

private String FormatWithoutHtmlEncode()
{
    decimal dVal = 21345.00M;
    String strFormatted = String.Format(System.Globalization.CultureInfo.CurrentCulture, "{0:c}", new object[] { dVal });
    System.Diagnostics.Debug.WriteLine(strFormatted);
    return strFormatted;
}

So the way to fix your problem with formatting would be to set HtmlEncode property to false. The above code that demonstrates this problem is included in the demo project of this article. After making this fix the code on ASPX looks like as follows.

<asp:GridView ID="ctlGridView" runat="server" autogeneratecolumns=False >
    <columns>
        <asp:boundfield datafield="ProductID" sortexpression="ProductID" />
        <asp:boundfield datafield="Name" headertext="Name" sortexpression="Name" />
        <asp:boundfield datafield="ProductNumber" headertext="Product Number" />
        <asp:BoundField DataField="ListPrice" HeaderText="List Price" 
                HtmlEncode="False" DataFormatString="{0:c}" />
        <asp:BoundField DataField="SellStartDate" HeaderText="Sell Start Date" 
                HtmlEncode="False" DataFormatString="{0:d}" />
    </columns>
</asp:GridView>

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionData formatting in GridView Pin
PeterScaletti17-May-14 22:18
PeterScaletti17-May-14 22:18 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.