- 积分
- 49
- 在线时间
- 77 小时
- 主题
- 8
- 注册时间
- 2014-11-19
- 帖子
- 91
- 最后登录
- 2017-12-27
- 帖子
- 91
- 软币
- 516
- 在线时间
- 77 小时
- 注册时间
- 2014-11-19
|
楼主 |
发表于 2015-5-21 10:53:52
|
显示全部楼层
19.检查数据的有效性
在gridview的ValidateRow事件中加入检查代码:
#region 检查数据 private void gridView1_ValidateRow(object sender, ValidateRowEventArgse) { GridView view = sender as GridView; view.ClearColumnErrors(); if (view.GetRowCellValue(e.RowHandle, "ReceiveDate") ==DBNull.Value) { e.Valid = false; view.SetColumnError(view.Columns["ReceiveDate"], "必须指定日期"); } } #endregion
调用gridview.UpdateCurrentRow()方法执行检查
最常用的DevExpress Winform 4个代码片段:
一 、GridControl的删除操作
private void rILinkEditInfoDel_Click(object sender, EventArgs e) { if (XtraMessageBox.Show("请确定是否删除当前记录?", "警告",MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes) { DataRow row =gvInfos.GetDataRow(gvInfos.FocusedRowHandle); delByCode(row["Code"].ToString()); XtraMessageBox.Show("操作成功!"); } }
二、绑定非数据表中列
Hashtable ht = new Hashtable(); private void gridView6_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgse) { GridView View = sender as GridView; if (e.RowHandle >= 0) { object needAlert =View.GetRowCellValue(e.RowHandle, View.Columns["needAlert"]); if (needAlert != null &needAlert != DBNull.Value && needAlert.ToString().Trim() !="0" & View.GetRowCellValue(e.RowHandle,View.Columns["Value"]) != DBNull.Value) { decimal AverValue = Convert.ToDecimal(View.GetRowCellValue(e.RowHandle,View.Columns["Value"])); objectMinValue = View.GetRowCellValue(e.RowHandle,View.Columns["MinValue"]); objectMaxVlaue = View.GetRowCellValue(e.RowHandle,View.Columns["MaxValue"]); if(MinValue != DBNull.Value & MinValue != null & MaxVlaue.ToString() !="" & MaxVlaue != DBNull.Value && MaxVlaue != null &MaxVlaue.ToString() != "") { decimal gridColumn2 = Convert.ToDecimal(View.GetRowCellValue(e.RowHandle,View.Columns["MinValue"])); decimal gridColumn1 = Convert.ToDecimal(View.GetRowCellValue(e.RowHandle,View.Columns["MaxValue"])); if (gridColumn2 > AverValue || AverValue > gridColumn1) { if (!ht.ContainsKey("pic")) ht.Add("pic", GetImage(1)); e.Value = ht["pic"]; } } } } } /// <summary> /// 由资源文件获取图片/// </summary> /// <param name="key"></param> /// <returns></returns> byte[] GetImage(int key) { Image img =DevExpress.Utils.Controls.ImageHelper.CreateImageFromResources(string.Format("RiverSys.Resources.{0}.gif",key.ToString()), typeof(RiverInfos).Assembly); returnDevExpress.XtraEditors.Controls.ByteImageConverter.ToByteArray(img,ImageFormat.Gif); }
/// <summary> /// 动态根据条件设置行样式/// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void gridView6_RowStyle(object sender,DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e) { GridView View = sender as GridView; if (e.RowHandle >= 0) { object needAlert =View.GetRowCellValue(e.RowHandle, View.Columns["needAlert"]); if (needAlert != null &needAlert != DBNull.Value && needAlert.ToString().Trim() !="0" & View.GetRowCellValue(e.RowHandle,View.Columns["Value"]) != DBNull.Value) { decimal AverValue = Convert.ToDecimal(View.GetRowCellValue(e.RowHandle, View.Columns["Value"])); objectMinValue = View.GetRowCellValue(e.RowHandle,View.Columns["MinValue"]); objectMaxVlaue = View.GetRowCellValue(e.RowHandle,View.Columns["MaxValue"]); if(MinValue != DBNull.Value & MinValue != null & MaxVlaue.ToString() !="" & MaxVlaue != DBNull.Value && MaxVlaue != null &MaxVlaue.ToString() != "") { decimal gridColumn2 = Convert.ToDecimal(MinValue); decimal gridColumn1 = Convert.ToDecimal(MaxVlaue); if (gridColumn2 > AverValue || AverValue > gridColumn1) { e.Appearance.ForeColor = Color.Red; e.Appearance.BackColor = Color.LightGray; } } } } }
三、GridControl 中颜色选择控件
private void gvMapColor_CustomUnboundColumnData(object sender,DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e) { GridView view = sender as GridView; DataView dv = view.DataSource as DataView; if (e.IsGetData) { string strVal =dv[e.ListSourceRowIndex]["Color"].ToString(); if (strVal != "") { //e.Value = DevExpress.Utils.StyleLayout.ColorFromString(strVal); e.Value = Common.HexToColor(strVal); } } else { //Color colorVal =DevExpress.Utils.StyleLayout.ColorFromString(e.Value.ToString()); Color colorVal =(Color)e.Value; dv[e.ListSourceRowIndex]["Color"] =Common.RGB_HEX(colorVal.ToArgb()); } }
四、关于 GridControl 验证示例
/**//// <summary> /// 初始化GridView,绑定数据/// </summary> /// <param name="parentId"></param> private void GridViewBindData(string parentId) { this.gridView1.Columns.Clear(); this.FDs= areaSetupActionHelper.getDsRegionByParentId(parentId); this.gridCArea.DataSource =this.FDs.Tables[0].DefaultView; this.gridView1.Columns["id"].VisibleIndex =-1; this.gridView1.Columns["childCounts"].VisibleIndex= -1; this.gridView1.Columns["reg_id"].Caption ="区划编号"; this.gridView1.Columns["reg_name"].Caption ="区划名称"; this.gridView1.Columns["parent_id"].Caption ="父区划编号"; this.gridView1.Columns["reg_desc"].Caption ="区划描述"; this.gridView1.Columns["parent_id"].ImageIndex =1; this.gridView1.Columns["reg_desc"].ImageIndex = 0; RepositoryItemTextEdit textEditReg_Id = newRepositoryItemTextEdit(); textEditReg_Id.Mask.EditMask =parentId+"\\d{2,3}"; textEditReg_Id.Mask.MaskType =DevExpress.XtraEditors.Mask.MaskType.Regular; this.gridView1.Columns["reg_id"].ColumnEdit =textEditReg_Id; this.gridView1.Columns["reg_desc"].ColumnEdit= new RepositoryItemMemoExEdit(); TreeListNode node =this.treelArea.FocusedNode.ParentNode; string fid =node==null?"0":node.GetValue("RegID").ToString().Trim(); DataSet ds =areaSetupActionHelper.getDsRegionByParentId(fid); RepositoryItemLookUpEdit lookUEParent_Id = newRepositoryItemLookUpEdit(); lookUEParent_Id.Columns.Add(newLookUpColumnInfo("reg_id", 40, "区划编号")); lookUEParent_Id.Columns.Add(newLookUpColumnInfo("reg_name", 40, "区划名称")); lookUEParent_Id.DataSource = ds.Tables[0].DefaultView; lookUEParent_Id.ValueMember = "reg_id"; lookUEParent_Id.DisplayMember = "reg_id"; this.gridView1.Columns["parent_id"].ColumnEdit =lookUEParent_Id; }
/**//// <summary> /// gridView单元格验证的相关处理程序/// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void gridView1_ValidatingEditor(objectsender, DevExpress.XtraEditors.Controls.BaseContainerValidateEditorEventArgs e) { if (e.Valid == false&this.gridView1.FocusedColumn.FieldName =="reg_id") { e.ErrorText = "区划编号不合法!\n应为父区划编号加2~3位数据组成!"; } if (this.gridView1.FocusedColumn.FieldName =="reg_name") { Regex reg=new Regex(@"[\u4e00-\u9fa5]{1,20}"); Match m=reg.Match(e.Value.ToString().Trim()); if (m.Length != e.Value.ToString().Trim().Length) { e.Valid = false; e.ErrorText = "区划名称应为汉字\n长度为1至20"; } } } private void gridView1_InvalidValueException(objectsender, InvalidValueExceptionEventArgs e) { if (MyDialog.Alert(" 您所填写的内容不符合规则\n 要放弃您刚才对此项所做的更改吗?", "您所编辑的内容不符合规则", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) ==DialogResult.Yes) { e.ExceptionMode = ExceptionMode.Ignore; } }
/**//// <summary> /// gridView行验证的相关处理程序/// </summary> private void gridView1_ValidateRow(objectsender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e) { string regid = this.gridView1.GetRowCellValue(e.RowHandle,"reg_id").ToString().Trim(); string regName = this.gridView1.GetRowCellValue(e.RowHandle,"reg_name").ToString().Trim(); if ( regid.Length < 1) { e.Valid = false; this.gridView1.SetColumnError(this.gridView1.Columns["reg_id"],"请填写区划编号!",DevExpress.XtraEditors.DXErrorProvider.ErrorType.Default); // e.ErrorText = "区划名称不能为空!"; } if (regName.Length < 1) { e.Valid = false; this.gridView1.SetColumnError(this.gridView1.Columns["reg_name"],"区划名称不能为空!",DevExpress.XtraEditors.DXErrorProvider.ErrorType.Default); } } private void gridView1_InvalidRowException(object sender,DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs e) { if (e.RowHandle >= 0) { if (this.gridView1.GetRowCellValue(e.RowHandle,this.gridView1.Columns["reg_id"]).ToString().Trim() == ""|| this.gridView1.GetRowCellValue(e.RowHandle,this.gridView1.Columns["reg_name"]).ToString().Trim() =="") { if (MyDialog.Alert(" 您所填写的内容不符合规则\n 要放弃您刚才对此项所做的更改吗?","您所编辑的内容不符合规则", MessageBoxButtons.YesNo,MessageBoxIcon.Warning) == DialogResult.Yes) { e.ExceptionMode = ExceptionMode.Ignore; } else { e.ExceptionMode = ExceptionMode.NoAction; } } } else { e.ExceptionMode = ExceptionMode.Ignore; } }
view plaincopy to clipboardprint? //获取焦点行任意单元格的数据 ColumnView cv = (ColumnView)gridControl_Gongzi.FocusedView;//重新获取此ID 否则无法从表头连删获取不到id int focusedhandle = cv.FocusedRowHandle; object rowIdObj = gridView1.GetRowCellValue(focusedhandle,"id"); if (DBNull.Value != rowIdObj) { FocusedRow_id = Convert.ToInt32(rowIdObj); } //获取焦点行任意单元格的数据ColumnView cv = (ColumnView)gridControl_Gongzi.FocusedView;//重新获取此ID 否则无法从表头连删获取不到id int focusedhandle = cv.FocusedRowHandle; object rowIdObj = gridView1.GetRowCellValue(focusedhandle, "id"); if (DBNull.Value != rowIdObj) { FocusedRow_id = Convert.ToInt32(rowIdObj); } view plaincopy to clipboardprint? //当数据发生变化时执行 private void gridView1_CellValueChanged(object sender,CellValueChangedEventArgs e) { int intRowHandle =e.RowHandle; FocusedRow_bumen =Convert.ToString(gridView1.GetRowCellValue(intRowHandle,"bumen")); FocusedRow_xingming =Convert.ToString(gridView1.GetRowCellValue(intRowHandle,"xingming")); //FocusedRow_jibengongzi =Convert.ToDecimal(gridView1.GetRowCellValue(intRowHandle,"jibengongzi")); object rowJibengongziObj =gridView1.GetRowCellValue(intRowHandle, "jibengongzi"); if (DBNull.Value !=rowJibengongziObj) { FocusedRow_jibengongzi = Convert.ToDecimal(rowJibengongziObj); } } //当数据发生变化时执行 private voidgridView1_CellValueChanged(object sender, CellValueChangedEventArgs e) { int intRowHandle= e.RowHandle; FocusedRow_bumen = Convert.ToString(gridView1.GetRowCellValue(intRowHandle,"bumen")); FocusedRow_xingming = Convert.ToString(gridView1.GetRowCellValue(intRowHandle,"xingming")); //FocusedRow_jibengongzi =Convert.ToDecimal(gridView1.GetRowCellValue(intRowHandle,"jibengongzi")); objectrowJibengongziObj = gridView1.GetRowCellValue(intRowHandle,"jibengongzi"); if(DBNull.Value != rowJibengongziObj) { FocusedRow_jibengongzi = Convert.ToDecimal(rowJibengongziObj); } } view plaincopy toclipboardprint? //设置焦点行的焦点单元格的位置 ColumnView view = (ColumnView)gridControl_Gongzi.FocusedView; view.FocusedColumn = view.Columns["bumen"]; //设置焦点行的焦点单元格的位置ColumnView view = (ColumnView)gridControl_Gongzi.FocusedView; view.FocusedColumn = view.Columns["bumen"]; view plaincopy toclipboardprint? //当焦点行发生改变时执行 获取选中焦点行id private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgse) { int intRowHandle =e.FocusedRowHandle; object rowIdObj =gridView1.GetRowCellValue(intRowHandle, "id"); if (DBNull.Value!= rowIdObj)//做个判断否则获取不到id后报错 { FocusedRow_id = Convert.ToInt32(rowIdObj); } } //当焦点行发生改变时执行 获取选中焦点行id private void gridView1_FocusedRowChanged(object sender,DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e) { intintRowHandle = e.FocusedRowHandle; objectrowIdObj = gridView1.GetRowCellValue(intRowHandle, "id"); if(DBNull.Value != rowIdObj)//做个判断否则获取不到id后报错 { FocusedRow_id = Convert.ToInt32(rowIdObj); } } view plaincopy to clipboardprint? //焦点行的FocusedHandle为: FocuseRow_Handle = -999998; //获取焦点行的handle ColumnView newview = (ColumnView)gridControl_Gongzi.FocusedView; FocuseRow_Handle = newview.FocusedRowHandle; //回车添加新行 private void gridView1_KeyPress(object sender, KeyPressEventArgse) { if(e.KeyChar == 13) { ColumnView view = (ColumnView)gridControl_Gongzi.FocusedView; if(view.IsLastRow) { if (FocuseRow_Handle == 0) { gridView1.AddNewRow(); ColumnView newview = (ColumnView)gridControl_Gongzi.FocusedView; newview.FocusedColumn = newview.Columns["bumen"];//定位焦点网格的位置 FocuseRow_Handle = newview.FocusedRowHandle;//获取新焦点行的FocuseRowHandle并初始化全局变量FocuseRow_Handle供保存操作时判断是update还是insert
9、如何显示水平滚动条?或
设置 this.gridView.OptionsView.ColumnAutoWidth = false;
.....列表宽度自适应内容
gridview1.BestFitColumns();
10、如何定位到第一条数据/记录?
设置 this.gridView.MoveFirst()
11、如何定位到下一条数据/记录?
设置 this.gridView.MoveNext()
12、如何定位到最后一条数据/记录?
设置 this.gridView.MoveLast()
13、设置成一次选择一行,并且不能被编辑
this.gridView1.FocusRectStyle = DevExpress.XtraGrid.Views.Grid.DrawFocusRectStyle.RowFocus;this.gridView1.OptionsBehavior.Editable = false;this.gridView1.OptionsSelection.EnableAppearanceFocusedCell = false;
14、如何显示行号?
private void gvPayList_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e) { e.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Far; 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(); } } }
15、如何让各列头禁止移动?
设置 gridView1.OptionsCustomization.AllowColumnMoving = false;
16、如何让各列头禁止排序?
设置 gridView1.OptionsCustomization.AllowSort = false;
17、如何禁止各列头改变列宽?
设置 gridView1.OptionsCustomization.AllowColumnResizing = false;
18.拖动滚动条时固定某一列
设置Columns,选择要固定的列。设置Fixed属性,可以选择:固定在左边、固定在右边、不固定。
19.获取选定行,指定列单元格的内容
return gridView1.GetRowCellValue(pRows[0], ColumName).ToString ();
20.分组显示
OptionsView>OptionsBehavior>AutoExpandAllGroups = True
选择要分组的列,将GroupIndex属性设置为0
21.格式化数据
private void gvList_ValidatingEditor(object sender, DevExpress.XtraEditors.Controls.BaseContainerValidateEditorEventArgs e) { if (this.gvList.FocusedColumn.FieldName == "passQty") { string passQty = e.Value.ToString().Trim(); int receiveQty = orderDetailList[this.gvList.FocusedRowHandle].qty; if (!JXType.IsIntBigThanZero(passQty)) { e.Valid = false; e.ErrorText = "合格数量必须为大于等于0小于等于接货数量的整数!"; } else { if (int.Parse(passQty) > receiveQty) { e.Valid = false; e.ErrorText = "合格数量必须为大于0小于等于接货数量的整数!"; } } } }
22.合并表头
///初始化表格 using DevExpress.XtraGrid.Columns;using DevExpress.XtraGrid.Views.Base;using DevExpress.XtraGrid.Views.BandedGrid;using DevExpress.XtraEditors.Repository; private void InitGrid() { // advBandedGridView1是表格上的默认视图,注意这里声明的是:BandedGridView BandedGridView view = advBandedGridView1 as BandedGridView; view.BeginUpdate(); //开始视图的编辑,防止触发其他事件 view.BeginDataUpdate(); //开始数据的编辑 view.Bands.Clear(); view.OptionsView.ShowColumnHeaders = false; //因为有Band列了,所以把ColumnHeader隐藏 //添加列标题 //添加列标题 GridBand bandID = view.Bands.AddBand("ID"); bandID.Visible = false; //隐藏ID列 GridBand bandName = view.Bands.AddBand("姓名"); GridBand bandSex = view.Bands.AddBand("性别"); GridBand bandBirth = view.Bands.AddBand("出生日期"); GridBand bandScore = view.Bands.AddBand("分数"); GridBand bandMath = bandScore.Children.AddBand("数学"); GridBand bandChinese = bandScore.Children.AddBand("语文"); GridBand bandEnglish = bandScore.Children.AddBand("英语"); GridBand bandSubTotal = bandScore.Children.AddBand("小计"); GridBand bandRemark = view.Bands.AddBand("备注"); bandFile.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;//这是合并表头居中显示 view.EndDataUpdate();//结束数据的编辑 view.EndUpdate(); //结束视图的编辑 }
具体可看
dev gridcontrol 合并表头
23. //动态添加列
DevExpress.XtraGrid.Columns.GridColumn Col1 = new DevExpress.XtraGrid.Columns.GridColumn(); Col1.FieldName = "name"; Col1.Caption = "名字"; Col1.Visible = false; Col1.VisibleIndex = gvCountry.Columns.Count; gvCountry.Columns.Add(Col1);
24。设置自动增加的行号
private void gridview_CustomDrawRowIndicator(object sender,DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e) {e.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Far; 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(); } }}
25.特效:gridcontrol中有5种view 型式,普通的是gridview,然后分别为cardview、BandedView、Advanced BandedView、LayoutView;共5种。
1)、view组中把OptionView下的viewmode 设置成“Carousel”就达到这种“旋转木马”式的gridcontrol view 特效了
2)、layoutView1.OptionsCarouselMode.PitchAngle 这个属性决定“旋转木马”的pitch angle 螺距角; 螺旋角; 螺旋升角; 俯仰角; 倾角; 节锥半角
3)、Roll Angle 属性决定着 倾侧角度
4)、指定数据源,显示数据:
//显示数据 private void showData(List<Employee > list) { DataTable dt = new DataTable("OneEmployee"); dt.Columns.Add("Caption", System.Type.GetType("System.String")); dt.Columns.Add("Department", System.Type.GetType("System.String")); dt.Columns.Add("PhotoName", System.Type.GetType("System.Byte[]")); for (int i = 0; i < list.Count; i++) { DataRow dr = dt.NewRow(); dr["Caption"] = list.Name; dr["Department"] = list.Department; string imagePath = @"D:\C#\photos\" + list.PhotoPath; dr["PhotoName"] = getImageByte(imagePath); dt.Rows.Add(dr); } gridControl1.DataSource = dt; } //返回图片的字节流byte[] private byte[] getImageByte(string imagePath) { FileStream files = new FileStream(imagePath, FileMode.Open); byte[] imgByte = new byte [files.Length ]; files.Read(imgByte, 0, imgByte.Length); files.Close(); return imgByte; }
26.检查数据的有效性
在gridview的ValidateRow事件中加入检查代码:
#region 检查数据 private void gridView1_ValidateRow(object sender, ValidateRowEventArgs e) { GridView view = sender as GridView; view.ClearColumnErrors(); if (view.GetRowCellValue(e.RowHandle, "ReceiveDate") == DBNull.Value) { e.Valid = false; view.SetColumnError(view.Columns["ReceiveDate"], "必须指定日期"); } }
27.设某一列文字和标题局中显示
gridView1.Columns[0].AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center; gridView1.Columns[0].AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
28.列表过滤条件多选
列名.OptionsFilter.FilterPopupMode= DevExpress.XtraGrid.Columns.FilterPopupMode.CheckedList
29.隔行换色的方法
this.gridView1.Appearance.OddRow.BackColor = Color.White; // 设置奇数行颜色 // 默认也是白色 可以省略 this.gridView1.OptionsView.EnableAppearanceOddRow = true; // 使能 // 和和上面绑定 同时使用有效 this.gridView1.Appearance.EvenRow.BackColor = Color.WhiteSmoke; // 设置偶数行颜色 this.gridView1.OptionsView.EnableAppearanceEvenRow = true; // 使能 // 和和上面绑定 同时使用有效
|
|