Format currency correctly in DevExpress Grid Control

Kevin DiTraglia picture Kevin DiTraglia · Oct 2, 2012 · Viewed 13.3k times · Source

So I've seen other questions on this, but I can't for the life of me make my grid format my float as currency. Here's my simple project, it has a grid control called gridcontrol1 with 4 columns, I want the last one to be currency, the other 3 to be string.

public partial class Form1 : Form
{
    private DevExpress.XtraGrid.GridControl gridControl1;
    private DevExpress.XtraGrid.Views.Grid.GridView gridView1;
    private DevExpress.XtraGrid.Columns.GridColumn gridColumn1;
    private DevExpress.XtraGrid.Columns.GridColumn gridColumn2;
    private DevExpress.XtraGrid.Columns.GridColumn gridColumn3;
    private DevExpress.XtraGrid.Columns.GridColumn gridColumn4;

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        ArrayList test = new ArrayList();
        test.Add(new MyObject() { myCurrency = 1.5F, prop1 = "hi", prop2 = "hi2", prop3 = "hi3" });

        gridColumn4.DisplayFormat.FormatString = "c";
        gridColumn4.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom;

        gridControl1.DataSource = test;
        gridControl1.MainView.PopulateColumns();
        gridControl1.RefreshDataSource();
    }
}

public class MyObject
{
    public string prop1 { get; set; }
    public string prop2 { get; set; }
    public string prop3 { get; set; }
    public float myCurrency { get; set; }
}

I have tried format string of 'c', 'c2', 'N', 'N2' and FormatType of both custom and numeric and any combination thereof with the same result of getting '1.5' listed in the box. Am I doing something simple wrong? This can't be that hard!

Answer

DmitryG picture DmitryG · Oct 2, 2012

Please, try the following (this works fine to me):

GridColumn colCurrency = gridView1.Columns["myCurrency"];
colCurrency.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom;
colCurrency.DisplayFormat.FormatString = "c";

Related link: GridColumn.DisplayFormat Property

Also remove the ColumnView.PopulateColumns command as GridView.Columns collection is cleared when this method is called. So, the Display format you set for columns in the designer does not affect the newly created column.