Question

I have an ASP.NET Gridview with a BoundField that is bound to a decimal value. I use the following code to format the decimal number to a currency value:

DataFormatString="{0:C}"

We have a custom implementation of NumberFormatInfo though, which removes the currency symbol and modifies the thousands seperator. Normally this format is applied as such:

myDecimal.ToString("C", myCustomNFI);

How do I specify a custom NumberFormatInfo on the BoundField element of the Gridview?

Thanks

Was it helpful?

Solution

This can be done using a custom bound field. Start with a custom BoundField class. Below I attempted to follow your naming convention.

namespace CustomBoundField
{
    public class NFIBoundField : System.Web.UI.WebControls.BoundField
    {
        protected override string FormatDataValue(object dataValue, bool encode)
        {
            if (dataValue == null || dataValue == System.DBNull.Value)
                return "";

            if (base.DataFormatString == string.Empty)
                return dataValue.ToString();

            // Format as you wish based on dataValue and DataFormatString argument
            return string.Format("{0}", dataValue);
        }
    }
}

Register the control in your .ASPX file:

<%@ Register Namespace="CustomBoundField" TagPrefix="custom" %>

Reference the custom BoundField inside your GridView:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
    <Columns>
        <custom:NFIBoundField  DataField="Price" HeaderText="Price" DataFormatString="{0:NFI}"/>
    </Columns>
</asp:GridView>

You will want to play around inside of FormatDataValue() in order to get the formatting you want.

A couple of comments:

  • If you want your custom BoundField to handle multiple formats, parse base.DataFormatString to get the formatting type. In other words, providing {0:NFI} or {0:NFI2} in the code-front could result in different formats if you accommodate for this within FormatDataValue.

  • You might want to consider creating your own format provider rather than placing all of your formatting logic right inside of the FormatDataValue function.

This approach should work for you just fine. Best of luck.

OTHER TIPS

Try with field.DataFormatString = currencySymbol + " {0:#,###.##}";

It works fine for me.

I'm not 100% certain but I don't think you can.

You'll need to use a template field and bind to a literal on RowDataBound instead using your custom formatter. Happy to be proved wrong however....

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top