DevExpress学习小结
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
以下内容为学习DevExpress过程中的以下总结:
1、Grid根据单元格设置行背景色:
private void gvTaskOrderDetail_RowCellStyle(object sender, RowCellStyleEventArgs e) {
GridView gv = sender as GridView;
Int32? goodsStockQty = CommonUtils.ObjectToInt32(
gv.GetRowCellValue(e.RowHandle,
gv.Columns.ColumnByFieldName("GOODSSTOCKQTY")));
Int32? productId = CommonUtils.ObjectToInt32(
gv.GetRowCellValue(e.RowHandle,
gv.Columns.ColumnByFieldName("TASKPRODUCTID")));
if (goodsStockQty != null)
{
if (goodsStockQty > 0)
{
e.Appearance.BackColor = Color.Pink;
}
else
{
if (productId == Constants.SMJH_ID)
{
e.Appearance.BackColor = Color.Pink;
}
}
}
else
{
if (productId == Constants.SMJH_ID)
{
e.Appearance.BackColor = Color.Pink;
}
}
}
2、c#程序查询oracle,在界面数据显示“?”,解决方法:
在客户的电脑新建环境变量,变量名为:NLS_LANG
值为:SIMPLIFIED CHINESE_CHINA.ZHS16GBK
3、数字控件去掉上下滚动箭头:
属性:
AllowMouseWheel:false
4、CheckedComboBoxEdit下拉多选控件的使用:
a、初始化:
foreach (DataRow dr in dt.Rows)
{
this.chkcbGoodsType.Properties.Items.Add(new
ComboxInfo(dr["GOODSTYPEID"].ToString(), dr["GOODSTYPENAME"].ToString()));
}
第二种方法:
CheckedListBoxItem[] itemListQuery = new CheckedListBoxItem[listCustomerType.Count];
int check = 0;
foreach (DictDetailVo det in listCustomerType)
{
itemListQuery[check] = new CheckedListBoxItem(det.DictDetailCode, det.DictDetailName);
check++;
}
this.chkcbCustomerType.Properties.Items.AddRange(itemListQuery);
b、后台赋值:(id和name对应)
第一种方法:this.chkcbGoodsType.EditValue = dt.Rows[0]["GOODSTYPEID"].ToString();
this.chkDriveTruckType.RefreshEditValue();
或者this.chkcbGoodsType.Text = dt.Rows[0]["GOODSTYPENAME"].ToString();
第二种方法this.chkcbGoodsType.EditValue =new CheckedListBoxItem( dt.Rows[0]["GOODSTYPEID"].ToString(),dt.Rows[0]["GOODSTYPENAME"].To String());
c、获取选中的值:
IList<object> list = this.chkcbGoodsType.Properties.Items.GetCheckedValues();
string goodsType=""; foreach (object obj in list)
{
goodsType += "," + ((ComboxInfo)obj).Code.ToString();
}
第二种方法:
string str=this.chkcbCustomerTypeQuery.EditValue;
5、ProgressBarControl进度条:
this.pBUpload.Properties.Maximum = 100;
this.pBUpload.Properties.Step = 1;
pBUpload.Position = 0;
for (int i = 1; i < 101; i++)
{
//处理当前消息队列中的所有windows消息
Application.DoEvents();
this.pBUpload.PerformStep();
}
6、GridControl添加按钮列:
把列的ColumnEdit属性设置为RepositoryItemButtonEdit
把TextEditStyle属性设置为HideTextEditor;
把Buttons的Kind属性设置为Glyph;
把Button的Caption用于设置文字
把Buttons的TextOption的Appearance的HAlignment属性设置为Near;
ButtonStyle设置为Office2003;
7、treeList展示到某一级
添加事件:NodesReloaded
TreeListNodes nodes = treeListProType.Nodes;
if (nodes != null && nodes.Count > 0)
{
foreach (TreeListNode node in nodes)
{
if (node.Level == 0)
{
node.Expanded = true;
}
}
}
8、布局控件禁用仍然显示文本标题:
设置:layoutControl1
Appearance--DisabledLayoutItem-ForeColor-ControlText;
Appearance--DisabledLayoutItem-Options-UseForeColor-True;
9、GridView某列用正则表达式限定编辑:
行编辑:
GridView某列用正则表达式时,从数据库绑定数据时,如果是数字类型的,要用to_char(det.demandqty) 转换;
10、日期控件DateEdit设置:
1、DateEdit,想要动态使其格式为"yyyy-MM-dd"或"yyyy-MM-dd HH:mm",用Mask属性设置
EditMask = 'yyyy/MM/dd HH:mm:ss',
UseMaskAsDisplayFormat = True
日期框显示时间的设置VistaDisplayMode
VistaEditTime
控件EditMask和DisplayFormat属性设置:yyyy/MM/dd HH:mm:ss
2、日期控件中如果包含了日期+时分秒,可采用如下设置:
设置以下属性
dateEdit1.Properties.VistaDisplayMode = DevExpress.Utils.DefaultBoolean.True;
dateEdit1.Properties.VistaEditTime = DevExpress.Utils.DefaultBoolean.True;
设置显示长日期模式(日期+时间):
dateEdit1.Properties.DisplayFormat.FormatString="g"
dateEdit1.Properties.DisplayFormat.FormatType=DateTime
dateEdit1.Properties.EditFormat.FormatString="g"
dateEdit1.Properties.EditFormat.FormatType=DateTime
设置为Vista模式时,如果要显示日期+时间的长日期模式,还需要设置:VistaTimeProperties.DisplayForm
3、日期控件只显示日期:
Mask--EditMask:yyyy/MM/dd
UseMaskAsDisplayFormat = True
11、右键菜单:
第一步:从工具箱中将BarManager拉入窗体
第二步:从工具箱中将PopupMenu拉入窗体,设置PopupMenu的Manager属性为barManager1。
第三步:右击PopupMenu在弹出的菜单内选中Customize,然后再弹出的对话框中,点击:弹出菜单编辑器,点击Add,新建右键菜单就OK了。
双击新建的菜单设置菜单点击事件;
第四步:在需要弹出右键菜单的控件上,使用xxxx_MouseUp事件弹出右键菜单,里添加以下代码段
//在表格显示右键菜单---在某个控件显示右键菜单
private void gridControl1_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
popupMenu1.ShowPopup(Control.MousePosition);
}
}
12、GridControl设置行背景色:
private void gvProduct_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
{
if (this.gvProduct.GetRow(e.RowHandle) == null)
{
return;
}
else
{
//获取所在行指定列的值
string state = this.gvProduct.GetRowCellValue(e.RowHandle, "ISCHECKED").ToString();
//比较指定列的状态
if (state == "True")
{
e.Appearance.BackColor = Color.BlueViolet;//设置此行的背景颜色
}
else
{
e.Appearance.BackColor = Color.White;//设置此行的背景颜色
}
}
}
13、GridLookUp下拉框显示高度:
下拉框的宽高,设置PopupFormSize的高度;
不显示滚动条:VertScrollVisibility 设置为never;
固定宽高:PopupSizeable 设置为false;
14、GridControl光标定位到某一个单元格:
this.gridView1.FocusedRowHandle = 1;//行标
this.gridView1.FocusedColumn = this.dictCode;//某一列
this.gridView1.ShowEditor();//打开行编辑
15、GridControl属性详解:
Options
OptionsBehavior 视图的行为选项
AllowIncrementalSearch 允许用户通过输入想得到的列值来定位行AllowPartialRedrawOnScrolling 允许视图在垂直滚动中局部刷新AutoExpandAllGroups 自动展开视图中的所有组
AutoPopulateColumns 当视图中没有某些数据源中的字段时,在视图中自动创建这些列
AutoSelectAllInEditor 在一个单元格编辑中,是否允许通过Enter或F2来选择该单元格的所有内容
AutoUpdateTotalSummary 当列值发生改变时,自动更新汇总摘要数据CacheValuesOnRowUpdating 缓冲将被存入数据源的数据(当一行数据要存入到数据源时,Grid可以将它的值存入到一个内部的缓冲器中。
这样,万一那行数据在存入时被数据源的检查机制清空了,还可以恢复)
Editable 允许对单元格进行编辑
EditorShowMode 设置鼠标激活单元格编辑器的模式
FocusLeaveOnTab 如果在Grid中TAB键被禁止,是否在按下TAB键时将焦点移到下一个控件
ImmediateUpdateRowPosition 因为排序、分组和过滤设置造成行的数据被修改时,是否立即更新一行的位置
16、lookupedit控件:
使用lookupedit1的值:
变量=this.lookupedit.editvalue.tostring()//是ookupedit.properties.valuemember的值
变量=this.lookupedit.text.trim()//是ookupedit.properties.displaymember 的值
特别值得注意的是,有时候我们要使用lookupedit来实现combox的一些效果,在实际的使用过程中在程序加载的时候会默认的选择第一项,它的设置是:
lookupedit.itemindex=0;//选择第一项
lookupedit.itemindex=-1;//无选项,此时显示的是nulltext值 其实这个地方只要editvalue==null,lookupedit就显示nulltext
lookupedit1.editvalue=value;//自动搜索datasouse,选择与之匹配的值,没有的情况下赋值null ,value的值必须与valuemember的数据类型一致。
只显示某列:
lp.Properties.Columns.Add(new
DevExpress.XtraEditors.Controls.LookUpColumnInfo("DictName"));
例子:
DataTable dtDict = new DataTable();
dtDict.Columns.Add("DictID", System.Type.GetType("System.Int32"));
dtDict.Columns.Add("DictName", System.Type.GetType("System.String"));
DataRow row = dtDict.NewRow();
row["DictID"] = 10000001;
row["DictName"] = "发货规则";
dtDict.Rows.Add(row);
DataRow row2 = dtDict.NewRow();
row2["DictID"] = 10000002;
row2["DictName"] = "区域等级";//区域等级taoyinghui@
dtDict.Rows.Add(row2);
lp.Properties.DataSource= dtDict;
lp.Properties.DisplayMember = "DictName";
lp.Properties.ValueMember = "DictID";
lp.Properties.Columns.Add(new
DevExpress.XtraEditors.Controls.LookUpColumnInfo("DictName"));
lp.ItemIndex = 0;//默认选中
获取key值:lp.EditValue.ToString()
17、treeList选中:
1.TreeList带有CheckBox,并且节点要有三种状态(所有的子节点都选中,所有的子节点都没选择,一部分子节点选中)。
使用DevXpress的TreeList控件很容易实现这一功能。
设置TreeList.OptionsView.ShowCheckBoxes = true //是否显示CheckBox
设置TreeList.OptionsBehavior.AllowIndeterminateCheckState = true; //设置节点是否有中间状态,即一部分子节点选中,一部分子节点没有选中
设置这两个属性之后就实现了TreeList带有CheckBox,并且节点有三种状态。
2.选中父节点或者子节点相互影响的功能,如选择父节点选择所有子节点。
绑定TreeList的两个事件AfterCheckNode和BeforeCheckNode
实现功能的代码如下:
private void treeList1_AfterCheckNode(object sender, DevExpress.XtraTreeList.NodeEventArgs e)
{
SetCheckedChildNodes(e.Node, e.Node.CheckState);
SetCheckedParentNodes(e.Node, e.Node.CheckState);
}
private void treeList1_BeforeCheckNode(object sender, DevExpress.XtraTreeList.CheckNodeEventArgs e)
{
e.State = (e.PrevState == CheckState.Checked ? CheckState.Unchecked : CheckState.Checked);
}
/// <summary>
/// 设置子节点的状态
/// </summary>
/// <param name="node"></param>
/// <param name="check"></param>
private void SetCheckedChildNodes(TreeListNode node, CheckState check)
{
for (int i = 0; i < node.Nodes.Count; i++)
{
node.Nodes[i].CheckState = check;
SetCheckedChildNodes(node.Nodes[i], check);
}
}
/// <summary>
/// 设置父节点的状态
/// </summary>
/// <param name="node"></param>
/// <param name="check"></param>
private void SetCheckedParentNodes(TreeListNode node, CheckState check)
{
if (node.ParentNode != null)
{
bool b = false;
CheckState state;
for (int i = 0; i < node.ParentNode.Nodes.Count; i++)
{
state = (CheckState)node.ParentNode.Nodes[i].CheckState;
if (!check.Equals(state))
{
b = !b;
break;
}
}
node.ParentNode.CheckState = b ? CheckState.Indeterminate : check;
SetCheckedParentNodes(node.ParentNode, check);
}
}
1.TreeList.NodeCellStyle事件
Node的显示(包括窗口的切换导致Node的显示)和状态的改变都会触发该事件。
该事件主要用来改变Node的显示样式。
private void treeList1_NodeCellStyle(object sender, DevExpress.XtraTreeList.GetCustomNodeCellStyleEventArgs e)
{
if (e.Node.CheckState == CheckState.Unchecked)
{
e.Appearance.Font = new Font(DevExpress.Utils.AppearanceObject.DefaultFont, FontStyle.Strikeout);
e.Appearance.ForeColor = Color.Gray;
}
}
上面的代码是实现的效果是:CheckState为Unchecked的节点的字带有中划线且背景灰色。
2.TreeList.DoubleClick事件
双击Node时触发,但要注意的是要在TreeList.OptionsBehavior.Editable = false的情况下,双击Node才能触发该事件。
private void treeList1_DoubleClick(object sender, EventArgs e)
{
TreeListNode clickedNode = this.treeList1.FocusedNode;
string disPlayText = clickedNode.GetDisplayText("test");
MessageBox.Show("You clicked " + disPlayText);
}
3.TreeList的命中测试特性
private void treeList1_MouseMove(object sender, MouseEventArgs e)
{
Point point = treeList1.PointToClient(Cursor.Position);
TreeListHitInfo hitInfo = treeList1.CalcHitInfo(point);
switch (hitInfo.HitInfoType)
{
case HitInfoType.Cell:
this.Cursor = Cursors.Hand;
break;
case HitInfoType.NodeCheckBox:
this.Cursor = Cursors.PanEast;
break;
default :
this.Cursor = Cursors.Default;
break;
}
}
18、Grid控件经典常用功能代码:
一、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.Reso urces.{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 = "区划编号不合法!\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(object sender, InvalidValueExceptionEventArgs e) {
if (MyDialog.Alert("您所填写的内容不符合规则\n要放弃您刚才对此项所做的更改吗?", "您所编辑的内容不符合规则", 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(" 您所填写的内容不符合规则\n要放弃您刚才对此项所做的更改吗?", "您所编辑的内容不符合规则", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
{
e.ExceptionMode = ExceptionMode.Ignore;
}
else
{
e.ExceptionMode = ExceptionMode.NoAction;
}
}
}
else
{
e.ExceptionMode = ExceptionMode.Ignore;
}
}。