代码如下:
public class DXGridControlHelper { /// <summary> /// 获取显示指定列的GridView /// </summary> /// <param name="grid"></param> /// <param name="columns">列集合</param> /// <returns></returns> public static DevExpress.XtraGrid.Views.Grid.GridView GetColumnsView(DevExpress.XtraGrid.GridControl grid, List<GridColumnModel> columns) { DevExpress.XtraGrid.Views.Grid.GridView view = new DevExpress.XtraGrid.Views.Grid.GridView(grid); foreach (GridColumnModel item in columns) { DevExpress.XtraGrid.Columns.GridColumn column = new DevExpress.XtraGrid.Columns.GridColumn(); column.FieldName = item.DataColumnName; column.Name = item.ColumnName; column.Caption = item.ColumnTitle; column.Visible = item.Visible; view.Columns.Add(column); } //下面指定分组,-1 为不分组 0,1,2....为分组顺序 (add的时候指定groupindex 无效,可能为列未在视图中初始化) for (int i = 0; i < columns.Count; i++) { view.Columns[i].GroupIndex =columns[i].GroupIndex; } return view; } } /// <summary> /// 动态创建gridView视图,列的Model /// </summary> public class GridColumnModel { /// <summary> /// 列表头文本 /// </summary> public string ColumnTitle { get; set; } /// <summary> /// 列唯一标识 name,默认为(column_sql语句中的字段名(小写)) /// column_sqlcolumnname /// </summary> private string _columnName; public string ColumnName { get { if (string.IsNullOrEmpty(_columnName)) return "column_" + DataColumnName.ToLower(); return _columnName; } set { _columnName = value; } } /// <summary> /// sql 语句中的字段名称 /// </summary> public string DataColumnName { get; set; } /// <summary> /// 可见性,默认true /// </summary> private bool? _visible; public bool Visible { get { if (_visible == null) return true; return bool.Parse(_visible.ToString()); } set { _visible = value; } } /// <summary> /// 分组,默认-1 /// </summary> private int? _groupIndex; public int GroupIndex { get { if (_groupIndex == null) { _groupIndex = -1; } return int.Parse(_groupIndex.ToString()); } set { _groupIndex = value; } } }
使用该代码 方法:
说明:动态制定的列 要与数据源中的列字段名(sql语句中的字段名) 一致
var view2 = DXGridControlHelper.GetColumnsView(gridControl1, new List<ColumnModel>() { new ColumnModel(){ColumnTitle="ID",DataColumnName="Id"},//默认该列为显示,列名为column_id new ColumnModel(){ColumnTitle="课件名称",GroupIndex=0,DataColumnName="Name"},//按照该列分组 new ColumnModel(){ColumnTitle="描述",DataColumnName="Description"}, new ColumnModel(){ColumnTitle="归属",DataColumnName="Objective"}, new ColumnModel(){ColumnTitle="图片",ColumnName="img",DataColumnName="ImgGif",Visible=false} }); DataTable tab = cl.GetDataTable("select * from table_name"); gridControl1.MainView = view2; gridControl1.DataSource = tab;
end;
时间: 2024-11-05 17:29:00