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 = "區劃編號不合法!\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";
}
}
}
privatevoid gridView1_InvalidValueException(object sender, InvalidValueExceptionEventArgs e)
{
if (MyDialog.Alert(" 您所填寫的內容不符合規則\n 要放棄您剛才對此項所做的更改嗎?", "您所編輯的內容不符合規則", 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(" 您所填寫的內容不符合規則\n 要放棄您剛才對此項所做的更改嗎?", "您所編輯的內容不符合規則", 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 = "區劃編號不合法!\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;
}
}
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控件小知識