c#devexpress xtragrid列格式

时间:2017-03-26 10:50:12

标签: c# devexpress xtragrid

我正在尝试在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";

1 个答案:

答案 0 :(得分:1)

在您的第一个示例中,有自动填充的可见列,并使用自定义格式显式创建隐藏列。当您明确添加列时,默认情况下会隐藏您的列。您需要通过将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";