简体   繁体   中英

Format currency correctly in DevExpress Grid Control

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!

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.

Instead of

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

Just move up the second line:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM