DevExpress 的Gridcontrol 之gridview 使用困惑?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了DevExpress 的Gridcontrol 之gridview 使用困惑?相关的知识,希望对你有一定的参考价值。
DevExpress 的Gridcontrol 控件怎么设置默认排序字段及排序方式。我在数据库查询中已经设置了排序字段。但是Gridcontrol 显示时会把查询的结果顺序打乱(还是那些被查询出来的数据。) 请高手指点,小弟迷茫中,不胜感激!!
这样试试run designer进入设置
layout视图
右键字段,第一个第二个就是排序。或者直接点击字段出现向上或向下的箭头就是排序了!
不明白hi我! 参考技术A designer---Column-- 选择要排序字段的sortorder--Ascending / Descending 参考技术B 是不是这样?GridView1.Columns 这是个集合啊
或者这样?GridView1.Rows[].Cells[] 这是单元格
你要所有的不就是集合么?
另外,站长团上有产品团购,便宜有保证
DevExpress之GridControl控件小知识
DevExpress之GridControl控件小知识
一.当代码中的DataTable中有建数据关系时,DevExpress 的 GridControl 会自动增加一个子视图 .列名也就是子表的字段名 ,按下面方法自定义子视图
DevExpress控件,当Table建立关系后,子表显示的Grid设置,在不设置的情况下默认显示一个Grid,但列头的名字为数据源的列名需要更改列头的描述必须自定义一个Grid,步骤:
1.[Clike here to create a new leve]点击此处创建一个Leve
2.单建刚建出的Leve右边的[Click here to change view]选择一个View类型
3.为GridControl增加LeveDefault,例如:
MyGridControl.LevelDefaults.Add(RelationName,gridview);
RelationName:DataSet中关系名
gridview:第二步建立的GridView的名称
二.DevExpress子视图的访问--当需要访问父视图中的行对应的子视图中的数据
DevExpress.XtraGrid.Views.Grid.GridView bv =(DevExpress.XtraGrid.Views.Grid.GridView) gvMain.GetDetailView(MyGridControl.FocusedRowHandle,0) ; //0是关系索引
for(int i=0 ;i<bv.DataRowCount ;i++)
{
bv.GetDataRow(i)["列名"] = 值 ;
}
三.视图中的列为DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit 类型,但不想让用户看到下拉按钮
编辑DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit控件,找到属性Buttons ,删除里面所有Button
四.DevExpress设置控件脚处的汇总格式
DevExpress控件SummaryItem.DisplayFormat={0:#} (数值类型)
==================================================================
devexpress 显示行号
为XtraGrid的GridView加行号。示例代码如下:
//设置行指示器的宽度(行指示器就是最左边那列什么都不显示的列)
//默认情况下,如果要在里面显示行号的话,宽度会不足,数字显示不清晰
//所以要改一下宽度
gv1.IndicatorWidth = 20;
private void gv1_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
{
if (e.Info.IsRowIndicator && e.RowHandle >= 0)
{
e.Info.DisplayText = (e.RowHandle + 1).ToString().Trim();
}
}
效果图如下:
常用代码:
//添加分组统计字段
gridView1.GroupSummary.Add(SummaryItemType.Count, "Product Name", gridView1.Columns["Product Name"]);
gridView1.GroupSummary.Add(SummaryItemType.Average, "Unit Price", gridView1.Columns["Unit Price"]);
//设置分组统计字段的显示格式
((GridSummaryItem)gridView1.GroupSummary[gridView1.GroupSummary.Count - 1]).DisplayFormat = "AVR={0:c}";
//设置分组字段
gridView1.Columns["Discontinued"].GroupIndex = 0;
//打开所有分组
gridView1.ExpandAllGroups();
//为控件画边框
ControlPaint.DrawBorder3D(e.Graphics,
r,
(e.Info.State == DevExpress.Utils.Drawing.ObjectState.Pressed ? Border3DStyle.SunkenOuter
: Border3DStyle.RaisedInner));
//焦点单元格的列
gridview1.FocusedColumn
//焦点单元格所在行的行号
gridview1.FocusedRowHandle
//焦点单元格的值
gridview1.FocusedValue
//指定单元格显示的字符串值
gridview1.GetRowCellDisplayText(int rowHandler,string feildName)
//指定单元格的值
gridview1.GetRowCellValue(int rowHandler,string feildName)
//设置焦点单元格所在行指定列的值
gridview1.SetFocusedRowCellValue(GridColumn col,object value)
//设置焦点单元格的值
gridview1.SetFocusedValue(object value)
//设置指定单元格的值
//有了这个函数,就可以手工创建行了。
gridview1.SetRowCellValue(int rowHandler,string feildName,object value)
gridview1.SetRowCellValue(int rowHandler,GridColumn col,object value)
//添加新行的方法
gv1.AddNewRow();
foreach (GridColumn col in gv1.Columns)
{
//用RowCount-1的办法是不行的
//gv1.SetRowCellValue(gv1.RowCount-1, col, "aaaaa");
gv1.SetRowCellValue(gv1.FocusedRowHandle, col, "aaaaa");
}
gv1.UpdateCurrentRow();
//根据绑定的数据源自动产生列
gv1.PopulateColumns();
//为列添加下拉列表(加其他类型如日期、UpDown同理)
RepositoryItemLookUpEdit ri = new RepositoryItemLookUpEdit();
//ri.PopupWidth = 200;
ri.DisplayMember = "sc_prna";
ri.ValueMember = "sc_prno";
DataTable dt1 = DbHelperSQL.QueryT("select sc_prno,sc_prna from mespb04h");
ri.DataSource = dt1;
gv1.Columns["sc_prno"].ColumnEdit = ri;
========================================================
DevExpress ,XtraGrid,GridControl,Gridview 使用点滴
1.在单元里显示日历控件、下拉框等
Imports DevExpress.XtraEditors.Repository
Dim irdata As New RepositoryItemCalcEdit
GridView1.Columns(1).ColumnEdit = irdata
2.格式化数字 ###,###.00
GridView1.Columns(4).DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric ‘此行必须要,不然下面的没有作用
GridView1.Columns(4).DisplayFormat.FormatString = "¥{0:N2}"
3.获得某单元格的值
GridView1.GetRowCellValue(GridView1.FocusedRowHandle, GridView1.FocusedColumn)
4.用代码显示分组
‘GridView1.OptionsView.ShowGroupPanel = False‘隐藏分组
GridView1.GroupSummary.Add(DevExpress.Data.SummaryItemType.Sum, "amount", GridView1.Columns("amount"), "小计:{0:N2}") ‘可以显示小计
GridView1.Columns("summary_id").GroupIndex = 2
GridView1.ExpandAllGroups() ‘ 初始就分组
‘当然不能少了一句:
GridView1.OptionsView.ShowFooter = True
5.代码设置过滤条件
GridView1.Columns("kmbm").FilterInfo = New ColumnFilterInfo(ColumnFilterType.Custom, Nothing, "[kmbm] like ‘%1001%‘ and [kmbm] like ‘%6%‘")
‘此处列名为kmbm , 区分大小写.
6.弹出菜单
PopupMenu1.ShowPopup(Control.MousePosition)
====================================================================
DevExpress 部分操作代码
///GridControl的删除操作
privatevoid 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();
privatevoid gridView6_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs 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"]));
object MinValue = View.GetRowCellValue(e.RowHandle, View.Columns["MinValue"]);
object MaxVlaue = 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);
return DevExpress.XtraEditors.Controls.ByteImageConverter.ToByteArray(img, ImageFormat.Gif);
}
/// <summary>
/// 动态根据条件设置行样式
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
privatevoid 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"]));
object MinValue = View.GetRowCellValue(e.RowHandle, View.Columns["MinValue"]);
object MaxVlaue = 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 中颜色选择控件
privatevoid 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>
privatevoid 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 = new RepositoryItemTextEdit();
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 = new RepositoryItemLookUpEdit();
lookUEParent_Id.Columns.Add(new LookUpColumnInfo("reg_id", 40, "区划编号"));
lookUEParent_Id.Columns.Add(new LookUpColumnInfo("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>
privatevoid gridView1_ValidatingEditor(object sender, DevExpress.XtraEditors.Controls.BaseContainerValidateEditorEventArgs e)
{
if (e.Valid == false&&this.gridView1.FocusedColumn.FieldName == "reg_id")
{
e.ErrorText = "区划编号不合法!
应为父区划编号加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 = "区划名称应为汉字
长度为1至20";
}
}
}
privatevoid gridView1_InvalidValueException(object sender, InvalidValueExceptionEventArgs e)
{
if (MyDialog.Alert(" 您所填写的内容不符合规则
要放弃您刚才对此项所做的更改吗?", "您所编辑的内容不符合规则", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
{
e.ExceptionMode = ExceptionMode.Ignore;
}
}
/**//// <summary>
/// gridView行验证的相关处理程序
/// </summary>
privatevoid gridView1_ValidateRow(object sender, 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);
}
}
privatevoid 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(" 您所填写的内容不符合规则
要放弃您刚才对此项所做的更改吗?", "您所编辑的内容不符合规则", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
{
e.ExceptionMode = ExceptionMode.Ignore;
}
else
{
e.ExceptionMode = ExceptionMode.NoAction;
}
}
}
else
{
e.ExceptionMode = ExceptionMode.Ignore;
}
}
===========================================================================
DevExpress 经典常用功能代码收集
Comments 0
随着DevExpress 控件包越来越多的被中国用户使用,由于是英文版本,看英文版使用说明非常困难,慧都控件网在DevExpress 控件包使用方面有多年的研究,慧都控件网会不断的把DevExpress 使用经验分享给大家。
下面是我们平时收集最常用的DevExpress Winform 4个代码片段,比较常用,希望对广大DEV用户有帮助。
一 、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.CustomColumnDataEventArgs 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"]));
object MinValue = View.GetRowCellValue(e.RowHandle, View.Columns["MinValue"]);
object MaxVlaue = 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);
return DevExpress.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"]));
object MinValue = View.GetRowCellValue(e.RowHandle, View.Columns["MinValue"]);
object MaxVlaue = 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 = new RepositoryItemTextEdit();
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 = new RepositoryItemLookUpEdit();
lookUEParent_Id.Columns.Add(new LookUpColumnInfo("reg_id", 40, "区划编号"));
lookUEParent_Id.Columns.Add(new LookUpColumnInfo("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(object sender, DevExpress.XtraEditors.Controls.BaseContainerValidateEditorEventArgs e)
{
if (e.Valid == false&this.gridView1.FocusedColumn.FieldName == "reg_id")
{
e.ErrorText = "区划编号不合法!
应为父区划编号加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 = "区划名称应为汉字
长度为1至20";
}
}
}
private void gridView1_InvalidValueException(object sender, InvalidValueExceptionEventArgs e)
{
if (MyDialog.Alert(" 您所填写的内容不符合规则
要放弃您刚才对此项所做的更改吗?", "您所编辑的内容不符合规则", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
{
e.ExceptionMode = ExceptionMode.Ignore;
}
}
/**//// <summary>
/// gridView行验证的相关处理程序
/// </summary>
private void gridView1_ValidateRow(object sender, 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(" 您所填写的内容不符合规则
要放弃您刚才对此项所做的更改吗?", "您所编辑的内容不符合规则", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
{
e.ExceptionMode = ExceptionMode.Ignore;
}
else
{
e.ExceptionMode = ExceptionMode.NoAction;
}
}
}
else
{
e.ExceptionMode = ExceptionMode.Ignore;
}
}
DevExpress DXperience是Windows和ASP.NET控件套包、IDE报表生成工具和企业应用程序框架。长期占据着慧都科技控件销量榜的第一位置。在慧都控件网的推动 下,DXperience帮助中国软件企业开发出很多优秀的软件产品 DXperience其产品的品牌、质量,是全球公认的。慧都控件网为 DXperience提供了全面的技术支持服务,同时提供 DXperience从入门到精通的控件培训服务 。
同时,慧都为DevExpress for .NET用户量身打造了一款中文资源包,DevExpress 官方汉化资源, 您只需极少花费便可获得这套完整、专业的汉化资源,从而使您的产品实现全面汉化。
DevExpress中国唯一正式授权的经销商慧都科技透露,DevExpress旗下著名控件套包:DXperience? Universal Subscription 即将更新到 v2010 vol 1,慧都控件网第一时间提供 DevExpress v2010 vol 1 控件套包下载,如需新版下载请联系慧都控件网。
=========================================================================
DevExpress GridControl 动态创建字段及主细关系表过程
在做项目中,往往需要在查询基类模板窗口内做主细关系Grid,引用一下代码可减少工作量,只需给此过程传递主、细SQL语句以及关联的关键字段即可完成如图所示的效果:
#region 执行主细查询过程
public void ExeQuery(string sMSql,string sDSql,string RelaitionField)
{
int iMCountItemNum = 0; int iDCountItemNum = 0;
int iMSumItemNum = 0; int iDSumItemNum = 0;
//查询。
if (sMSql == null || sMSql == "" || sDSql == null || sDSql == "")
{
return;
}
#region 根据SQL填充主、细表
using (OracleConnection connection = new OracleConnection(DbHelperOra.connectionString))
{
_dtQuery = new DataSet();
try
{
connection.Open();
OracleDataAdapter command = new OracleDataAdapter(sMSql, connection);
command.Fill(_dtQuery, "MA");
command.SelectCommand.CommandText=sDSql;
command.Fill(_dtQuery,"DE");
command.Dispose();
}
catch (System.Data.OracleClient.OracleException ex)
{
}
finally
{
connection.Close();
}
}
#endregion
#region 主表动态构造字段。
try
{
//获取到表结构。
if (_dtQuery.Tables["MA"].Rows.Count >= 0)
{
gvMainList.Columns.Clear();
gvMainList.GroupSummary.Clear();
gvMainList.ClearGrouping();
//gvMainList.OptionsBehavior.Editable = true;
int iVisible = 0;
//根据表结构动态加载到GridControl控件中。
foreach (DataColumn _dcQuery in _dtQuery.Tables["MA"].Columns)
{
iVisible++;
//动态添加
DevExpress.XtraGrid.Columns.GridColumn gcQueryList = new DevExpress.XtraGrid.Columns.GridColumn();
gcQueryList.Name = "_dc" + _dcQuery.ColumnName.ToUpper();
gcQueryList.Caption = _dcQuery.ColumnName;
gcQueryList.FieldName = _dcQuery.ColumnName;
//数字类型
if ((_dcQuery.DataType.ToString().ToUpper() == "SYSTEM.DECIMAL" || _dcQuery.DataType.ToString().ToUpper() == "SYSTEM.DOUBLE") &&
((gcQueryList.Caption.IndexOf("金额") >= 0) || (gcQueryList.Caption.IndexOf("价格") >= 0)
|| (gcQueryList.Caption.IndexOf("人民币") >= 0) || (gcQueryList.Caption.IndexOf("美元") >= 0)
|| (gcQueryList.Caption.IndexOf("单价") >= 0) || (gcQueryList.Caption.IndexOf("个") >= 0)
|| (gcQueryList.Caption.IndexOf("件") >= 0) || (gcQueryList.Caption.IndexOf("箱") >= 0)
|| (gcQueryList.Caption.IndexOf("数量") >= 0)) && iMSumItemNum < 1)
{
iMSumItemNum++;
gcQueryList.SummaryItem.FieldName = _dcQuery.ColumnName;
gcQueryList.SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Sum;
gvMainList.GroupSummary.Add(DevExpress.Data.SummaryItemType.Sum, _dcQuery.ColumnName, null, " 小计:{0}");
}
else if ((_dcQuery.DataType.ToString().ToUpper() == "SYSTEM.DECIMAL" || _dcQuery.DataType.ToString().ToUpper() == "SYSTEM.STRING") &&
((gcQueryList.Caption.IndexOf("序号") >= 0) || (gcQueryList.Caption.IndexOf("流水") >= 0)
|| (gcQueryList.Caption.IndexOf("ID") >= 0) || (gcQueryList.Caption.IndexOf("编号") >= 0)
|| (gcQueryList.Caption.IndexOf("箱号") >= 0) || (gcQueryList.Caption.IndexOf("尺寸") >= 0)
|| (gcQueryList.Caption.IndexOf("序") >= 0) || (gcQueryList.Caption.IndexOf("单号") >= 0)) && iMCountItemNum < 1)
{
iMCountItemNum++;
gcQueryList.SummaryItem.FieldName = _dcQuery.ColumnName;
gcQueryList.SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Count;
gvMainList.GroupSummary.Add(DevExpress.Data.SummaryItemType.Count, _dcQuery.ColumnName, null, " 小计:{0}");
}
if (gcQueryList.FieldName != null && RelaitionField != null && gcQueryList.FieldName.ToUpper() != RelaitionField.ToUpper())
{
gcQueryList.VisibleIndex = iVisible;
gcQueryList.Visible = true;
}
else
{
gcQueryList.VisibleIndex = -1;
gcQueryList.Visible = false;
}
//gcQueryList.ColumnEdit.ReadOnly = true;
gvMainList.Columns.Add(gcQueryList);
}
}
gcMainList.MainView = gvMainList;
}
catch (System.Exception ex)
{
MsgBox.ErrorMsg("执行查询失败! 失败原因:" + ex.Message);
}
#endregion
#region 子表构造字段
try
{
//获取到表结构。
if (_dtQuery.Tables["DE"].Rows.Count >= 0)
{
DevExpress.XtraGrid.Views.Grid.GridView gvMainDetail = new DevExpress.XtraGrid.Views.Grid.GridView();
// gvMainDetail.Columns.Clear();
// gvMainDetail.GroupSummary.Clear();
// gvMainDetail.ClearGrouping();
// gvMainDetail.OptionsBehavior.Editable = true;
int iVisible = 0;
//根据表结构动态加载到GridControl控件中。
foreach (DataColumn _dcQueryDetail in _dtQuery.Tables["DE"].Columns)
{
iVisible++;
//动态添加
DevExpress.XtraGrid.Columns.GridColumn gcDetialQueryList = new DevExpress.XtraGrid.Columns.GridColumn();
gcDetialQueryList.Name = "_dcD" + _dcQueryDetail.ColumnName.ToUpper();
gcDetialQueryList.Caption = _dcQueryDetail.ColumnName;
gcDetialQueryList.FieldName = _dcQueryDetail.ColumnName;
//数字类型
if ((_dcQueryDetail.DataType.ToString().ToUpper() == "SYSTEM.DECIMAL" || _dcQueryDetail.DataType.ToString().ToUpper() == "SYSTEM.DOUBLE") &&
((gcDetialQueryList.Caption.IndexOf("金额") >= 0) || (gcDetialQueryList.Caption.IndexOf("价格") >= 0)
|| (gcDetialQueryList.Caption.IndexOf("人民币") >= 0) || (gcDetialQueryList.Caption.IndexOf("美元") >= 0)
|| (gcDetialQueryList.Caption.IndexOf("单价") >= 0) || (gcDetialQueryList.Caption.IndexOf("个") >= 0)
|| (gcDetialQueryList.Caption.IndexOf("件") >= 0) || (gcDetialQueryList.Caption.IndexOf("箱") >= 0)
|| (gcDetialQueryList.Caption.IndexOf("数量") >= 0)) && iDSumItemNum < 1)
{
iDSumItemNum++;
gcDetialQueryList.SummaryItem.FieldName = _dcQueryDetail.ColumnName;
gcDetialQueryList.SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Sum;
gvMainDetail.GroupSummary.Add(DevExpress.Data.SummaryItemType.Sum, _dcQueryDetail.ColumnName, null, " 小计:{0}");
}
else if ((_dcQueryDetail.DataType.ToString().ToUpper() == "SYSTEM.DECIMAL" || _dcQueryDetail.DataType.ToString().ToUpper() == "SYSTEM.STRING") &&
((gcDetialQueryList.Caption.IndexOf("序号") >= 0) || (gcDetialQueryList.Caption.IndexOf("流水") >= 0)
|| (gcDetialQueryList.Caption.IndexOf("ID") >= 0) || (gcDetialQueryList.Caption.IndexOf("编号") >= 0)
|| (gcDetialQueryList.Caption.IndexOf("箱号") >= 0) || (gcDetialQueryList.Caption.IndexOf("尺寸") >= 0)
|| (gcDetialQueryList.Caption.IndexOf("序") >= 0) || (gcDetialQueryList.Caption.IndexOf("单号") >= 0)) && iDCountItemNum < 1)
{
iDCountItemNum++;
gcDetialQueryList.SummaryItem.FieldName = _dcQueryDetail.ColumnName;
gcDetialQueryList.SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Count;
gvMainDetail.GroupSummary.Add(DevExpress.Data.SummaryItemType.Count, _dcQueryDetail.ColumnName, null, " 小计:{0}");
}
if (gcDetialQueryList.FieldName != null && RelaitionField != null && gcDetialQueryList.FieldName.ToUpper() != RelaitionField.ToUpper())
{
gcDetialQueryList.VisibleIndex = iVisible;
gcDetialQueryList.Visible = true;
}
else
{
gcDetialQueryList.VisibleIndex = -1;
gcDetialQueryList.Visible = false;
}
//gcDetialQueryList.ColumnEdit.ReadOnly = true;
gvMainDetail.Columns.Add(gcDetialQueryList);
}
gcMainList.ViewCollection.Add(gvMainDetail);
}
}
catch (System.Exception ex)
{
MsgBox.ErrorMsg("执行查询失败! 失败原因:" + ex.Message);
}
#endregion
#region 建立关系并填充数据源
_dtQuery.Relations.Add("RMD", _dtQuery.Tables["MA"].Columns[RelaitionField], _dtQuery.Tables["DE"].Columns[RelaitionField], false);
gcMainList.DataSource = _dtQuery.Tables["MA"];
gvMainList.BestFitColumns();
#endregion
}
#endregion
======================================================================
evExpress 2.0 GridControl 使用方法
关于GridControl的几点介绍
1. 它的功能类似与 Visual Studio .NET 2003自带的 DataGrid ,用于数据的客户端展示。开发者可以领用程序控制进行分页现实,分页方法在此不予介绍了。
2. 它与DataGrid的不同就在于其功能的非常强大,可以直接设计报表并可导出为Excel,Txt,Hmtl 格式。免去了再用其他控件设计报表的烦杂。
常用的几个对象
private DevExpress.XtraGrid.GridControl gridControl1;//整个数据容器
private DevExpress.XtraGrid.Views.BandedGrid.BandedGridView bandedGridView1;//显示容器
private DevExpress.XtraGrid.Views.BandedGrid.GridBand gridBand1;//用于设计表头
private DevExpress.XtraGrid.Views.BandedGrid.BandedGridColumn bandedGridColumn1;//用于数据项
之间的关系如下
gridControl1 包含 GridView ,BandedGridView,CarView 以及 AdvBandedGridView,其中bandedGridView又包含 GridBand 和 BandedGridColumn,下面本文以bandedGridView 为列作一使用介绍.
设计样图
步骤一:
将控件拖至设计窗体中,点击 Click here to change view 转换默认gridView为bandedGridView 样式,因为此样式可以给数据设计表头。
步骤二:
点击 Run Designer 进入设计界面入下图
步骤三:
图中 1 框选的按钮功能为添加 数据项bandedGridColumn1 ,根据字段的多少进行添加,
每个字段对应一个数据项。
步骤四:图中 3框选的按钮功能为添加 表头gridBand1,根据需要的数据进行添加。
步骤五:
添加完数据项和表头就需要进行样式设计,即图中2框选的按钮功能。可以自由的进行表头拖动合并,仅需鼠标即可完成,十分方便快捷。如果在字段数量较大的情况,建议使用程序进行控制,因为过多的字段在有限的屏幕中很难控制。
设计过程中gridBand1的放置在表头最底层上bandedGridColumn进行一一对应。为了不显示bandedGridColumn名称,可将属性中的Caption 设置为空字符即一个空格。
代码控制片段
oracleConnection conn = null;
oracleCommand command = null;
try
{
conn = DBConnection.GetConnection();
command = new oracleCommand(m_query_elqc_sql,conn);
oracleDataAdapter oraAdapter = new oracleDataAdapter(command);
DataSet ds = new DataSet();
oraAdapter.Fill(ds);
if(ds.Tables.Count < 1 ) return ;
DataTable dt = ds.Tables[0];
gridControl1.DataSource = dt;
//绑定数据
gridColumn1.FieldName = dt.Columns[0].ColumnName;
gridColumn2.FieldName = dt.Columns[1].ColumnName;
gridColumn3.FieldName = dt.Columns[2].ColumnName;
gridColumn4.FieldName = dt.Columns[3].ColumnName;
gridColumn5.FieldName = dt.Columns[4].ColumnName;
gridColumn6.FieldName = dt.Columns[5].ColumnName;
gridColumn7.FieldName = dt.Columns[6].ColumnName;
gridColumn8.FieldName = dt.Columns[7].ColumnName;
gridColumn9.FieldName = dt.Columns[8].ColumnName;
gridColumn10.FieldName = dt.Columns[9].ColumnName;
gridColumn11.FieldName = dt.Columns[10].ColumnName;
gridColumn12.FieldName = dt.Columns[11].ColumnName;
gridColumn13.FieldName = dt.Columns[12].ColumnName;
}
finally
{
conn.Close();
}
如果需要通过代码进行表头和数据项的设计,可参阅“Windows 窗体设计器生成的代码”中自动生成的方法.
导出报表
仅需如下一步即可完成
this.gridControl1.ExportToExcel(m_savefilename);
存在的不足
1 字段过多不易显示
2 导出报表后字体的样式和表头的背景颜色丢失
=================================================================
以上是关于DevExpress 的Gridcontrol 之gridview 使用困惑?的主要内容,如果未能解决你的问题,请参考以下文章