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
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.
Try with field.DataFormatString = currencySymbol + " {0:#,###.##}";
It works fine for me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With