DisplayFormat 设置显示格式如:{0:P}表示显示为百分号模式。如数据源中为0.5。表示出来为50%
2、GridContro总合计及分组合计:
常规总合计直接RunDesigner-Group Summary Items
DisplayFormat 设置显示格式如:{0:P}表示显示为百分号模式。如数据源中为0.5。表示出来为50%
FieldName 设置显示的对应列
ShowInGroupColumnFooter 在那一列下面显示
SummaryType 合计方式。选择Custom表示自定义。CustomSummaryCalculate事件可处理
//Footer行自定义列合计 GridView view = sender as GridView; if (e.Item == view.Columns["RateZk"].SummaryItem) { decimal x = Convert.ToDecimal(view.Columns["RetailFAmount"].SummaryItem.SummaryValue); decimal y = Convert.ToDecimal(view.Columns["RetailAmount"].SummaryItem.SummaryValue); view.Columns["RateZk"].SummaryItem.DisplayFormat = "{0:P}"; ) e.TotalValue = x / y; else e.TotalValue = ; }
GridContro导出Excel操作:
SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Title = "导出Excel"; saveFileDialog.Filter = "Excel文件(*.xls)|*.xls"; DialogResult dialogResult = saveFileDialog.ShowDialog(this); if (dialogResult == DialogResult.OK) { this.gvbrowse.OptionsPrint.AutoWidth = false; //设置导出的Excel自动调整列宽,列宽和控件的列宽一致 this.gcbrowse.ExportToXls(saveFileDialog.FileName); //this.gcbrowse.ExportToXlsOld(saveFileDialog.FileName);//这个方法默认会自动调整列宽,但是office10以上版本有的会报错 DevExpress.XtraEditors.XtraMessageBox.Show("保存成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); this.gvbrowse.OptionsPrint.AutoWidth = true; }
GridControl列要显示百分号:
Run Designer-Columns列 FormatType="Numeric" FormatString="p"
自动调整所有字段宽度 this.gridView1.BestFitColumns();
显示滚动条:gridView1.OptionsView.ColumnAutoWidth属性是true,即各列的宽度自动调整,你把它设成false,就会出现了。
设置奇、偶行交替颜色
OptionsView.EnableAppearanceEvenRow =
true;
OptionsView.EnableAppearanceOddRow =
true
;
MultiSelect = true; //设置可多选
MultiSelectMode =CellSelect/RowSelect;//多选行还是多选单元格(一般选RowSelect)
//禁用标题行过滤
AllowFilter = false;
//禁用标题行排序
AllowSort = false;
//禁止列移动
AllowColumnMoving = false;
//禁止改变列宽
AllowColumnResizing = false;
FocusRectStyle = None; //取消点击后的虚线框
下拉框清空
1、清值 comboboxedit2.editvalue=null;
2、清列表 comboboxedit2.properties.items.clear();
GridView 设置选中行的颜色
GridView : Run Designer -> Appearences : selectRow & FocusedRow (两项都要设置)
BackColor : MediumSlateBlue 背景色
ForeColor : White 前景色 字体颜色
GridView 设置标题行以及内容行 数据居中
标题行 10 所述 在HeadPanel 里有一个TextOptions 展开之后 将HAlignment : Center
如果是将内容行数据居中.有两种方法 1 : 逐行设置 2 : 设置Appearences
1 : GridView -> Run Designer -> Columns -> AppearanceCell -> TextOptions 找到HAlignment : Center .
2 : GridView -> Run Designer -> Appearance -> ViewCaption -> TextOptions -> HAlignment : Center
GridView 添加 序号 列
GridView : Run Designer -> Event -> CustomDrawRowIndicator
在事件中添加代码
public static void DrawRowIndicator(this GridView gridView, int width = 40, string headTitle = "行号") { gridView.CustomDrawRowIndicator += (sender, e) => { e.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center; if (e.Info.Kind == DevExpress.Utils.Drawing.IndicatorKind.Header) { e.Appearance.DrawBackground(e.Cache, e.Bounds); e.Appearance.DrawString(e.Cache, headTitle, e.Bounds); e.Handled = true; } if (e.Info.IsRowIndicator) { if (e.RowHandle >= 0) { e.Info.DisplayText = (e.RowHandle + 1).ToString(); } else if (e.RowHandle < 0 && e.RowHandle > -1000) { e.Info.Appearance.BackColor = System.Drawing.Color.AntiqueWhite; e.Info.DisplayText = "G" + e.RowHandle.ToString(); } } }; gridView.IndicatorWidth = width != 0 ? width : 40; }
另外在 Run Desginer -> IndicatorWidth 设置序号列的宽度 一般50左右就比较适合一些了.
汉化按钮提示:
public class ChEditLocalizer : Localizer { // 重载 GetLocalizedString 方法 public override string GetLocalizedString(StringId id) { switch (id) { //Button 按钮汉化 case StringId.XtraMessageBoxOkButtonText: return "确认"; case StringId.XtraMessageBoxCancelButtonText: return "取消"; case StringId.XtraMessageBoxAbortButtonText: return "退出"; case StringId.XtraMessageBoxRetryButtonText: return "重试"; case StringId.XtraMessageBoxIgnoreButtonText: return "忽略"; case StringId.XtraMessageBoxYesButtonText: return "是"; case StringId.XtraMessageBoxNoButtonText: return "否"; } return base.GetLocalizedString(id); } }
public class XtraGrid_CN : GridLocalizer { public override string GetLocalizedString(GridStringId id) { switch(id) { case GridStringId.ColumnViewExceptionMessage:return "是否进行更正?"; } return base.GetLocalizedString(id); } }
皮肤设置:
DevExpress.UserSkins.OfficeSkins.Register(); //注册office的皮肤 请先加入引用office的dll文件,关于如何引用 请看下文 DevExpress.UserSkins.BonusSkins.Register(); //注册BonusSkins的皮肤 if (!DevExpress.Skins.SkinManager.AllowFormSkins) DevExpress.Skins.SkinManager.EnableFormSkins(); DevExpress.LookAndFeel.UserLookAndFeel.Default.SkinName = "Black"; //默认黑背景
DevExpress实现GridView当无数据行时提示消息 https://ctolib.com/topics-51130.html
/// <summary> /// 设置当没有数据行的提示信息『CustomDrawEmptyForeground』 /// </summary> /// <param name="gridView">GridView</param> /// <param name="e">CustomDrawEventArgs</param> /// <param name="noRecordMsg">提示信息</param> public static void DrawNoRowCountMessage(this GridView gridView, CustomDrawEventArgs e, string noRecordMsg) { if (gridView == null) throw new ArgumentNullException("gridView"); if (gridView.RowCount == 0) { if (!string.IsNullOrEmpty(noRecordMsg)) { Font _font = new Font("宋体", 10, FontStyle.Bold); Rectangle _r = new Rectangle(e.Bounds.Left + 5, e.Bounds.Top + 5, e.Bounds.Width - 5, e.Bounds.Height - 5); e.Graphics.DrawString(noRecordMsg, _font, Brushes.Black, _r); } } }
代码使用方法如下:
private void gvLampTotal_CustomDrawEmptyForeground(object sender, DevExpress.XtraGrid.Views.Base.CustomDrawEventArgs e) { gvLampTotal.DrawNoRowCountMessage(e, "暂无符合的数据!"); }
DevExpress实现GridControl列头绘制Checkbox的方法 https://ctolib.com/topics-51144.html http://aloysians.com/blog/getInfo/52837/1491226375
/// <summary> /// 为列头绘制CheckBox /// </summary> /// <param name="view">GridView</param> /// <param name="checkItem">RepositoryItemCheckEdit</param> /// <param name="fieldName">需要绘制Checkbox的列名</param> /// <param name="e">ColumnHeaderCustomDrawEventArgs</param> public static void DrawHeaderCheckBox(this GridView view, RepositoryItemCheckEdit checkItem, string fieldName, ColumnHeaderCustomDrawEventArgs e) { /*说明: *参考:https://www.devexpress.com/Support/Center/Question/Details/Q354489 *在CustomDrawColumnHeader中使用 *eg: * private void gvCabChDetail_CustomDrawColumnHeader(object sender, DevExpress.XtraGrid.Views.Grid.ColumnHeaderCustomDrawEventArgs e) * { * GridView _view = sender as GridView; * _view.DrawHeaderCheckBox(CheckItem, "Check", e); * } */ if (e.Column != null && e.Column.FieldName.Equals(fieldName)) { e.Info.InnerElements.Clear(); e.Painter.DrawObject(e.Info); DrawCheckBox(checkItem, e.Graphics, e.Bounds, getCheckedCount(view, fieldName) == view.DataRowCount); e.Handled = true; } } private static void DrawCheckBox(RepositoryItemCheckEdit checkItem, Graphics g, Rectangle r, bool Checked) { CheckEditViewInfo _info; CheckEditPainter _painter; ControlGraphicsInfoArgs _args; _info = checkItem.CreateViewInfo() as CheckEditViewInfo; _painter = checkItem.CreatePainter() as CheckEditPainter; _info.EditValue = Checked; _info.Bounds = r; _info.PaintAppearance.ForeColor = Color.Black; _info.CalcViewInfo(g); _args = new ControlGraphicsInfoArgs(_info, new DevExpress.Utils.Drawing.GraphicsCache(g), r); _painter.Draw(_args); _args.Cache.Dispose(); } private static int getCheckedCount(GridView view, string filedName) { int count = 0; for (int i = 0; i < view.DataRowCount; i++) { object _cellValue = view.GetRowCellValue(i, view.Columns[filedName]); if (_cellValue == null) continue; if (string.IsNullOrEmpty(_cellValue.ToString().Trim())) continue; bool _checkStatus = false; if (bool.TryParse(_cellValue.ToString(), out _checkStatus)) { if (_checkStatus) count++; } } return count; }
使用方法如下:
RepositoryItemCheckEdit CheckItem = new RepositoryItemCheckEdit(); const string gcCheckFieldName = "Checked"; private void gvLampConfig_CustomDrawColumnHeader(object sender, ColumnHeaderCustomDrawEventArgs e) { GridView _view = sender as GridView; _view.DrawHeaderCheckBox(CheckItem, gcCheckFieldName, e); }
实际写法:
private bool _mCheckStatus; //选中状态 private void gvCrabsRequisition_CustomDrawColumnHeader(object sender, DevExpress.XtraGrid.Views.Grid.ColumnHeaderCustomDrawEventArgs e) { if (e.Column != null && e.Column.FieldName == "CheckState") { e.Info.InnerElements.Clear(); e.Painter.DrawObject(e.Info); DevControlHelper.DrawCheckBox(e, _mCheckStatus); e.Handled = true; } } public static void DrawCheckBox(ColumnHeaderCustomDrawEventArgs e, bool chk) { var repositoryCheck = e.Column.ColumnEdit as RepositoryItemCheckEdit; if (repositoryCheck == null) return; var g = e.Graphics; var r = e.Bounds; var info = repositoryCheck.CreateViewInfo() as CheckEditViewInfo; var painter = repositoryCheck.CreatePainter() as CheckEditPainter; if (info == null) return; info.EditValue = chk; info.Bounds = r; info.CalcViewInfo(g); var args = new ControlGraphicsInfoArgs(info, new GraphicsCache(g), r); painter?.Draw(args); args.Cache.Dispose(); } private void gvCrabsRequisition_Click(object sender, EventArgs e) { if (DevControlHelper.ClickGridCheckBox(gvCrabsRequisition, "CheckState", _mCheckStatus)) { _mCheckStatus = !_mCheckStatus; } }
默认的数字、日期等输入,都要切换输入法才可以输入,不能默认就支持数字的输入,那么是否有办法解决呢
记得逢数字,日期的控件,必须设置 ImeMode=Off 。
设置指定列可以编辑
private void gvCrabsRequisition_ShowingEditor(object sender, CancelEventArgs e) { GridView _view = sender as GridView; List<string> editList = new List<string>() { "colWarehouseRequisedActualAmountAdd", "colCheckState" }; if (editList.Contains(_view.FocusedColumn.Name) == false) { e.Cancel = true; } }
设置gridview默认属性
/// <summary> /// 设置girdView默认属性 /// </summary> /// <param name="gv"></param> public static void SetStyle(DevExpress.XtraGrid.Views.Grid.GridView gv) { /* * author:wxm * date :2014年7月25日10:59:08 * */ gv.OptionsView.ShowGroupPanel = false; //不允许自定义分组 gv.RowHeight = 22; //行高22 gv.OptionsView.ShowFooter = false; //不显示页脚 //表头行高设置为24、分组行高设置为35(为仅有一级分组的行高) gv.ColumnPanelRowHeight = 24; gv.GroupRowHeight = 35; //列表中最前面的空白列的宽度设置为12 gv.IndicatorWidth = 12; //设置列表是否多选、多选的模式(行或单元格)、选择的行或单元格背景是否倒置 gv.OptionsSelection.MultiSelect = false; gv.OptionsSelection.MultiSelectMode = DevExpress.XtraGrid.Views.Grid.GridMultiSelectMode.RowSelect; gv.OptionsSelection.InvertSelection = false; gv.OptionsSelection.EnableAppearanceFocusedCell = false; //允许编辑 gv.OptionsBehavior.Editable = true; //不显示分组面板 gv.OptionsView.ShowGroupPanel = false; //不允许用户进行过滤和分组 gv.OptionsCustomization.AllowFilter = false; gv.OptionsCustomization.AllowGroup = false; //允许用户拖动列和不允许进行列排序 gv.OptionsCustomization.AllowColumnMoving = true; gv.OptionsCustomization.AllowSort = false; //列标题垂直居中 gv.Appearance.HeaderPanel.Options.UseTextOptions = true; gv.Appearance.HeaderPanel.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center; gv.Appearance.HeaderPanel.TextOptions.VAlignment = DevExpress.Utils.VertAlignment.Center; //将数据行内容垂直,文字左对齐,数字右对齐 //gv.Appearance.Row.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center; //gv.Appearance.Row.TextOptions.VAlignment = DevExpress.Utils.VertAlignment.Center; //HAlignment(水平位置):Far(数字右对齐)/Near(文字、日期左对齐) //不显示右键菜单 gv.OptionsMenu.EnableColumnMenu = false; //自动过滤时不显示过滤记录 gv.OptionsView.ShowFilterPanelMode = DevExpress.XtraGrid.Views.Base.ShowFilterPanelMode.Never; }
参考:https://zhidao.baidu.com/question/1174521530470594219.html
校验数据有效性:
/// <summary> /// 校验更改后单元格数据有效性 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void gvCrabsRequisition_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e) { try { var list = gcCrabsRequisition.DataSource as List<GetCrabStockRequisitionItem>; if (list.IsHasRow()) { var lstCheck = list.Where(r => r.CheckState).ToList(); //选中1个才校验 if (lstCheck.Count == 1) { GridView view = sender as GridView; GridColumn _productId = view.Columns["ProductId"];//原料Id GridColumn _submitAmount = view.Columns["WarehouseRequisedActualAmountAdd"];//本次调拨数量 Guid productId = (Guid)view.GetRowCellValue(e.RowHandle, _productId); var cellAmout = view.GetRowCellValue(e.RowHandle, _submitAmount); decimal submitAmount = cellAmout.IsNull() ? 0 : (decimal)cellAmout; //var serachAmount = _kvSerchActualAmountList.FirstOrDefault(s => s.Key == productId).Value; var regex = new Regex(@"^d+$"); //正则 判断非负整数 if (regex.IsMatch(submitAmount.ToString())) { view.SetColumnError(_submitAmount,"本次调拨数量在更改后必须是正整数!"); } //if (submitAmount > serachAmount) //{ // e.Valid = false; // view.SetColumnError(_submitAmount, "数量在更改后不能超过之前查询的结果值,请检查!"); // return; //} if (submitAmount <= 0 || string.IsNullOrEmpty(submitAmount.ToString())) { e.Valid = false; view.SetColumnError(_submitAmount, "数量在更改后大于0才能提交,请检查!"); return; } if (e.Valid) { view.ClearColumnErrors(); } } } } catch (Exception ex) { MessageCommon.ShowWar($"校验异常:{ex.Message}"); } }
DevExpress中GridControl中实现checkbox多行选中
在我们要绑定的容器中添加一个新列
我用的是DataTable 在DataTable中添加一个新列代码如下
//新建一个数据表 probll.GetProductAll自己写的方法 DataTable db = probll.GetProductAll(4, pageIndex, "申请中", 0, out pageCount); //在表中增加一个列 add(列名,列类型) db.Columns.Add("check", typeof(bool)); //给每一行的该列赋值 for (int i = 0; i < db.Rows.Count; i++) { db.Rows[i]["check"] = "false"; }
注意:新增列的类型为bool类型
设置可以多选
gridView1 .OptionsSelection.MultiSelect = true; gridView1 .OptionsSelection.MultiSelectMode = DevExpress.XtraGrid.Views.Grid.GridMultiSelectMode.RowSelect;
设置获取选中行的需要值
string value=""; string strSelected=""; for (int i = 0; i < gridView1.RowCount; i++) { // 获取选中行的check的值 value = gridView1.GetDataRow(i)["check"].ToString(); if (value == "True") { // productid 是我绑定数据表的字段 可以自己根据需求定义 这样就可以实现文中开始处的功能了 strSelected += gridView1.GetRowCellValue(i, "productid"); } }
原文:http://blog.csdn.net/l1158513573/article/details/46502569
gridControl:给该列添加组件(如按钮) 三种方法 法一:打开设计器(Run Designer),选择左侧Repository,点击In-place Editor Repository(内嵌编辑器),点击Add右侧的下拉菜单 ,选择你想添加的控件,比如ComboBoxEdit,再在右侧编辑控件的属性,ComboBox的话就可以设置Data下的Items集合,然后点左侧 Main里的Columns,点你想在上头添加控件的列,找右侧Data下的ColumnEdit,点最右边的下拉菜单,点Existing左侧的加号,就能找 到你刚才的控件,添加。会默认给该列的每一个格都加上这个控件。 法二:点击你想添加控件的列标题,再点属性栏中的ColumnEdit,下拉菜单点new,选择想添加的控件,然后Column Edit左侧会出现加 号,展开加号,下方会出现许多子属性,这些都是设置内嵌的控件的属性的。 法三:直接写代码。 ② 拖动一个gridControl控件,改变视图为BandedGridview,属性栏中点OptionView,选择NewItemRowPosition,选Bottom ②添加引用:usingDevExpress.XtraGrid.Views.BandedGrid; form的构造函数中添加代码: BandedGridColumn newColumn = bandedGridView1.Columns.Add() as BandedGridColumn; newColumn.Caption = "Country"; bandedGridView1.Bands[0].Columns.Add(newColumn); newColumn.Visible = true; ②(假设添加的控件是计算器)添加引用:usingDevExpress.XtraEditors.Repository; form的构造函数中继续添加代码,效果图 RepositoryItemCalcEdit calcEdit = new RepositoryItemCalcEdit(); gridControl.RepositoryItems.Add(calcEdit); newColumn.ColumnEdit = calcEdit;
原文: http://blog.csdn.net/qq_30756923/article/details/77982536 整理GridControl层级表格及按钮列
参考:
http://www.cnblogs.com/DeepLearing/p/3887601.html DevExpress GridView 那些事儿
http://blog.csdn.net/wsnwxm/article/details/7486606 DevExpress控件汉化教程详解
http://blog.csdn.net/wsnwxm/article/details/7483900 DXperience皮肤设置 C#第三方控件学习笔记
http://group.pandorabox.cn/forum.php?mod=viewthread&tid=266 汉化提示
https://ctolib.com/topics-51073.html
DevExpress根据条件设置GridControl RepositoryItem(设定指定列)是否可编辑
http://www.cnblogs.com/DeepLearing/p/3927358.html 修改DevExpress中英文提示,将英文改为中文
http://www.cnblogs.com/YanZhiwei/p/3277455.html [DevExpress]实现GridControl输入验证
http://www.cnblogs.com/wuhuacong/archive/2012/07/17/2595182.html DevExpress控件开发常用要点(项目总结版)
http://blog.csdn.net/yangyifan0/article/details/11988585 DEVexpress GridControl 属性设置