DevExpress的 GridControl 各种操作技巧

1、GridControl

/// <summary>
/// 初始化GridControl
/// </summary>
/// <param name="gc"></param>
public static void InitGridControl(GridControl gc,object  obj, bool showNav)
{
    gc.DataSource = obj;
    // 显示页面行数导航栏
    gc.UseEmbeddedNavigator = showNav;
    // 不显示新增按钮
    gc.EmbeddedNavigator.Buttons.Append.Visible = false;
    // 不显示编辑按钮
    gc.EmbeddedNavigator.Buttons.Edit.Visible = false;
    // 不显示删除编辑按钮
    gc.EmbeddedNavigator.Buttons.CancelEdit.Visible = false;
    // 不显示删除按钮
    gc.EmbeddedNavigator.Buttons.Remove.Visible = false;
    // 不显示保存按钮
    gc.EmbeddedNavigator.Buttons.EndEdit.Visible = false;
    // 设置行数显示字符串,第一个参数当前选中行,第二个参数 总行数
    gc.EmbeddedNavigator.TextStringFormat = "当前第 {0} 行,共 {1} 行 ";
    // 设置行数显示字符串 的颜色
    gc.EmbeddedNavigator.ForeColor = Color.Red;
    // 设置行数显示字符串 的显示位置
    gc.EmbeddedNavigator.TextLocation = DevExpress.XtraEditors.NavigatorButtonsTextLocation.Center;
            
    // 提示信息
    gc.EmbeddedNavigator.Buttons.First.Hint = "第一页";
    gc.EmbeddedNavigator.Buttons.PrevPage.Hint = "上一页";
    gc.EmbeddedNavigator.Buttons.Prev.Hint = "上一行";
    gc.EmbeddedNavigator.Buttons.Next.Hint = "下一行";
    gc.EmbeddedNavigator.Buttons.NextPage.Hint = "下一页";
    gc.EmbeddedNavigator.Buttons.Last.Hint = "最后一页";

    // GridControl选中后'ctrl+del'删除行
    gc.ProcessGridKey += (s, e) =>
    {
        if (e.KeyCode == Keys.Delete && e.Modifiers == Keys.Control)
        {
            if (XtraMessageBox.Show("是否删除选中行?", "警告信息", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                GridControl grid = s as GridControl;
                GridView view = grid.FocusedView as GridView;
                view.DeleteSelectedRows();
            }
            else
            {
                return;
            }
        }
    };
    gc.DataSourceChanged += (s, e) =>
    {
        GridView view = gc.MainView as GridView;
        // 解决 GridControl 记录能获取而没有显示出来的问题
        view.PopulateColumns();               
    };
}

image

2、GridView

1、初始化

/// <summary>
/// 初始化GridView
/// </summary>
/// <param name="gv"></param>
/// <param name="groupName">GridView的标题</param>
/// <param name="allowEdit">是否允许编辑</param>
/// <param name="showHscrollbar">是否显示水平滚动条</param>
/// <param name="di">列的顺序、显示位置、宽度等</param>
///  di :new Dictionary<string, string>
///                     字段名  , 中文表头|宽度|位置|格式化
///                     位置:1:居中靠左,2:居中;3:居中靠右    
public static void InitGridView(GridView gv, string groupName, bool allowEdit,bool showHscrollbar, Dictionary<string, string> di)
{
    // 是否显示分组面板
    gv.OptionsView.ShowGroupPanel = false;
    gv.GroupPanelText = groupName;
    //// 新增行的显示位置
    //gv.OptionsView.NewItemRowPosition = NewItemRowPosition.Top;
    // 是否允许合并单元格 默认为false
    gv.OptionsView.AllowCellMerge = false;
    // 是否显示自动筛选行 默认为false
    gv.OptionsView.ShowAutoFilterRow = false;
    // 是否自动行高,默认为false
    gv.OptionsView.RowAutoHeight = false;
    // 让各列头禁止移动
    gv.OptionsCustomization.AllowColumnMoving = false;
    // 让各列头禁止排序?
    gv.OptionsCustomization.AllowSort = false;
    // 禁止各列头改变列宽?
    gv.OptionsCustomization.AllowColumnResizing = false;      
    // 整行选中
    gv.OptionsBehavior.EditorShowMode = DevExpress.Utils.EditorShowMode.Click;
    // 是否允许编辑
    gv.OptionsBehavior.Editable = allowEdit;
    // 禁用 GridControl 中单击列弹出右键菜单
    //gv.OptionsMenu.EnableColumnMenu = false;
    // 奇数行变色 AllowCellMerge 必须为false
    gv.OptionsView.EnableAppearanceOddRow = true;
    gv.Appearance.OddRow.BackColor = Color.AliceBlue;
    // 偶数行变色
    gv.OptionsView.EnableAppearanceEvenRow = true;
    gv.Appearance.EvenRow.BackColor = Color.AntiqueWhite;
            
    // 设置行指示器的宽度
    gv.IndicatorWidth = 60;

    // 显示水平滚动条
    if (showHscrollbar)
    {
        gv.OptionsView.ColumnAutoWidth = false;
    }
    else
    {
        gv.BestFitColumns();
    }
            

    // 显示行号
    gv.CustomDrawRowIndicator += (s, e) =>
    {
        if (e.Info.IsRowIndicator && e.RowHandle >= 0)
        {
            e.Info.DisplayText = (e.RowHandle + 1).ToString().Trim();
        }
    };

    // 设置GridView的字段、表头等,必须放在GridControl.DataSource之前
    List<string> list = new List<string>(di.Keys);
    for (int i = 0; i < list.Count; i++)
    {
        string[] str = di[list[i]].Split('|');
        GridColumn col = new GridColumn()
        {
            Name = list[i],
            FieldName = list[i],
            Caption = str.Length < 1?"": str[0],
            VisibleIndex = i
        };
        gv.Columns.Add(col);
    }
            
    for (int i = 0; i < gv.Columns.Count; i++)               
    {
        string[] str = di[list[i]].Split('|');
        GridColumn col = gv.Columns[i];
        // 宽度
        col.Width = Convert.ToInt32(str.Length < 2 ? "75" : str[1]);
        col.AppearanceHeader.TextOptions.VAlignment = DevExpress.Utils.VertAlignment.Center;
        // 位置
        switch (str.Length < 3 ? "1" : str[2])
        {
            case "1":
                col.AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Near;
                break;
            case "2":
                col.AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
                break;
            case "3":
                col.AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Far;
                break;
            default:
                col.AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Default;
                break;
        }
        // 格式化
        col.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom;
        col.DisplayFormat.FormatString = str.Length < 3 ? "" : str[3];
                
    }
}

2、为数据指定下拉窗体

private void FrmGridControl_Load(object sender, EventArgs e)
    {
        string sql = "select dept_code,dept_name from dept_dict";
        DataTable dtDept = DbHelperOracle.Query(sql).Tables[0];
	// 为GridView绑定下拉数据
        RepositoryItemLookUpEdit rilu = new RepositoryItemLookUpEdit();
        rilu.DataSource = dtDept;
        rilu.DisplayMember = "DEPT_NAME";
        rilu.ValueMember = "DEPT_CODE";
        gridView1.Columns["DEPT_CODE"].ColumnEdit = rilu;
		
	// 加一个计算列,必须显示脚注
	gridView1.OptionsView.ShowFooter = true;
	gridView1.Columns["NAME"].SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Count;
	gridView1.Columns["NAME"].SummaryItem.FieldName = "NAME";
	gridView1.Columns["NAME"].SummaryItem.DisplayFormat = "合计:{0} 人";
    }

3、指定字段设置属性

// 为姓名字段设置渐变色
GridColumn columnName = gridView1.Columns["NAME"];
columnName.Caption = "姓名";
columnName.AppearanceCell.BackColor = Color.DarkBlue;
columnName.AppearanceCell.BackColor2 = Color.LightBlue;
columnName.AppearanceCell.ForeColor = Color.White;

4、获取焦点的数据

// 获取焦点单元格的列
GridColumn col = gridView1.FocusedColumn;
// 获取焦点所在的行
int row = gridView1.FocusedRowHandle;
// 焦点单元格的值
string name = gridView1.FocusedValue.ToString();

3、导出数据

也可以直接调用this.gridControl1.ShowRibbonPrintPreview();进行数据的预览、打印等等;

/// <summary>
/// 导出Excel
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void BtnExport_Click(object sender, EventArgs e)
{
    if (gridControl1.MainView.RowCount > 0)
    {
        SaveFileDialog dlg = new SaveFileDialog();
        dlg.Title = "导出Excel";
        dlg.Filter = "Excel文件(*.xlsx)|*.xlsx";
        DialogResult result = dlg.ShowDialog(this);
        if (result == DialogResult.OK)
        {
            XlsExportOptions options = new XlsExportOptions();
            gridControl1.ExportToXlsx(dlg.FileName);
            if (XtraMessageBox.Show("保存成功!是否打开文件?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
            {
                System.Diagnostics.Process.Start(dlg.FileName);
            }
        }
    }
    else
    {
        XtraMessageBox.Show("没有需要导出的数据", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
}

4、调用示例

/// <summary>
/// 获取数据
/// </summary>
private void GetData()
{   
    // 自定义网格数据
    InitData();
    Dictionary<string, string> di = new Dictionary<string, string>
            {
               { "NAME","姓名|80|2|"},
               { "ID_NO", "身份证|150|1|" },
               { "TCQ", "统筹区|80|1|" },
               { "START_DATE", "开始日期|120|2|yyyy-MM-dd" },
               { "END_DATE", "结束日期|120|2|yyyy-MM-dd" },
               { "MTB_CODE", "慢特病代码|160|1|" },
               { "MTB_NAME", "慢特病名称|200|1|" }
            };
            GetData();
            gridControl1.DataSource = dataSource.Tables[0];
            
            InitGridControl(gridControl1, true);
            InitGridView(gridView1, " ", true, false, di);
}

5、添加计算列的方法

5.1 方法一

// 增加一个计算列  
gv.OptionsView.ShowFooter = true;
GridGroupSummaryItem ggItem = new GridGroupSummaryItem
{
       FieldName = "NAME",
       ShowInGroupColumnFooter = gv.Columns["NAME"],
       SummaryType = SummaryItemType.Count,
       DisplayFormat = "合计:{0:c2}"
};
gv.GroupSummary.Add(ggItem);

5.1 方法二

// 加一个计算列,必须显示脚注
gridView1.OptionsView.ShowFooter = true;
gridView1.Columns["NAME"].SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Count;
gridView1.Columns["NAME"].SummaryItem.FieldName = "NAME";
gridView1.Columns["NAME"].SummaryItem.DisplayFormat = "合计:{0} 人";
posted @ 2022-05-21 10:39  his365  阅读(1566)  评论(0编辑  收藏  举报