时间:2019-03-08 标签:c#devexpressxtragridcolumnformat

c# devexpress xtragrid column format

我正在尝试在 XtraGrid 组件中设置列的自定义格式:

public class Customers
{
    public object A { get; set; }
}

Customers c61 = new Customers();
c61.A = DateTime.Now.AddDays(1);

Customers c62 = new Customers();
c62.A = DateTime.Now.AddDays(3);

List<Customers> tmpList = new List<Customers>();
tmpList.Add(c61);
tmpList.Add(c61);

gridControl1.DataSource = tmpList;

GridColumn gc = new GridColumn();
(gridControl1.MainView as GridView).Columns.AddRange(new DevExpress.XtraGrid.Columns.GridColumn[] { gc });

gc.Caption = "A";
gc.FieldName = "A";

(gridControl1.MainView as GridView).Columns["A"].DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
(gridControl1.MainView as GridView).Columns["A"].DisplayFormat.FormatString = "dd/MM/yyyy";

它不起作用。但是当我简单地删除显式添加列时,XtraGrid 会自动填充列并且格式工作正常。工作代码:

Customers c61 = new Customers();
c61.A = DateTime.Now.AddDays(1);

Customers c62 = new Customers();
c62.A = DateTime.Now.AddDays(3);

List<Customers> tmpList = new List<Customers>();
tmpList.Add(c61);
tmpList.Add(c61);

gridControl1.DataSource = tmpList;

(gridControl1.MainView as GridView).Columns["A"].DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
(gridControl1.MainView as GridView).Columns["A"].DisplayFormat.FormatString = "dd/MM/yyyy";

在您的第一个示例中,有自动填充的可见列和使用自定义格式显式创建的隐藏列。当您显式添加列时,您的列默认隐藏。您需要通过将 GridColumn.Visible 属性 设置为 true 或使用其 GridColumn.VisibleIndex 属性 来显示它。此外,当您显式添加列时,最好使用 GridView.OptionsBehavior.AutoPopulateColumns 属性.
关闭网格视图的自动填充 这是示例:

Customers c61 = new Customers();
c61.A = DateTime.Now.AddDays(1);

Customers c62 = new Customers();
c62.A = DateTime.Now.AddDays(3);

List<Customers> tmpList = new List<Customers>();
tmpList.Add(c61);
tmpList.Add(c61);

var view = gridControl1.MainView as GridView;
view.OptionsBehavior.AutoPopulateColumns = false; // <= Turn off the autopulation before assign the data source.

gridControl1.DataSource = tmpList;

GridColumn gc = new GridColumn();

view.Columns.AddRange(new DevExpress.XtraGrid.Columns.GridColumn[] { gc });

gc.Caption = "A";
gc.FieldName = "A";
gc.Visible = true; // <= Unhide your column.

view.Columns["A"].DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
view.Columns["A"].DisplayFormat.FormatString = "dd/MM/yyyy";