C# DevExpress控制元件Gridview和GridControl學習總結
去年公司開始啟動做自己的ERP物流系統,我也從Android客戶端轉向C#客戶端開發,以下是在開發專案中遇到的一些知識點,記錄下來,畢竟好記性不如爛筆頭。
1、 如何解決單擊記錄整行選中的問題
View->OptionsBehavior->EditorShowMode 設定為:Click
GridView view = sender as GridView;
view.OptionsBehavior.EditorShowMode = DevExpress.Utils.EditorShowMode.Click;
GridColumn col = view.FocusedColumn as GridColumn;
if (col.ReadOnly)
{
e.Cancel = true;
return;
}
DataRowView currentRowView = (DataRowView)bdMain.Current;
DataRow currentRow = currentRowView.Row as DataRow;
if (currentRow.RowState == DataRowState.Unchanged)
{
e.Cancel = ((dbModule.rightsValue & XfRightsDefine.RIGHTS_EDIT) == 0);
}
2、 如何新增一條記錄
(1)、gridView.AddNewRow();
(2)、給新行繫結資料,然重新整理行 gridView.UpdateCurrentRow();
(3)、關閉編輯狀態,gridView.CloseEditor,接受改變 gridView.AcceptChanges(),否則就資料回滾gridView.RejectChanges();
//新增一行
this.grdContract.AddNewRow();
DataRow dtContractRow = this.grdContract.GetFocusedDataRow();
if (dtContractRow == null) return;
dtContractRow["SITEID"] = DataTypeUtil.ConvertToString(dRow["SITEID"]);
dtContractRow["DEFINEID"] = DataTypeUtil.ConvertToString(dRow["DEFINEID"]);
dtContractRow["CONTDEPT"] = contractId;
dtContractRow["DEPTNAME"] = contractName;
this.grdContract.UpdateCurrentRow();
this.grdContract.CloseEditor();
string errMsg = string.Empty;
bool bOk = DbActionUtil.SaveData(dbModule, 1012, dTable, DataViewRowState.Added, out errMsg);
if (!bOk)
{
dtMain.RejectChanges();
MessageDxUtil.ShowError(errMsg);
}
3、如何解決 GridControl 記錄能獲取而沒有顯示出來的問題
//gridView.populateColumns();
grdViewDet.PopulateColumns();
grdDet.DataSource = bdDet;
grdViewDet.Columns["XF_DB_SORT_COLUMN"].Visible = false;
grdViewDet.BestFitColumns();
GridUtil.showFooterSum(bdDet, grdViewDet);
4、如何讓行只能選擇而不能編輯(或編輯某一單元格)
(1)、View->OptionsBehavior->EditorShowMode 設定為:Click
(2)、View->OptionsBehavior->Editable 設定為:false
5、如何顯示行號
grdMain.IndicatorWidth = 50;
grdMain.CustomDrawRowIndicator += gv_CustomDrawRowIndicator;
grdMain.FocusRectStyle = DrawFocusRectStyle.RowFocus;
/// <summary>
/// 顯示行號
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void gv_CustomDrawRowIndicator(object sender, RowIndicatorCustomDrawEventArgs e) {
//文字居中
e.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
if (e.Info.IsRowIndicator && e.RowHandle > -1) {
e.Info.DisplayText = (e.RowHandle + 1).ToString();
}
}
6、如何隱藏 GridControl 的 GroupPanel 表頭
設定 Run Design->OptionsView->ShowGroupPanel 設定為:false
7、如何禁用 GridControl 中列頭的過濾器 過濾器如下圖所示:
設定 Run Design->OptionsCustomization->AllowFilter 設定為:false
8、設定隔行預設顏色
grdMain.OptionsView.EnableAppearanceEvenRow = true;
grdMain.OptionsView.EnableAppearanceOddRow = true;
9、如何顯示水平滾動條?
設定 this.gridView.OptionsView.ColumnAutoWidth = false;
10、列表寬度自適應內容
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、批量選擇;選擇複製
grdMain.OptionsSelection.MultiSelect = true;
grdMain.OptionsSelection.MultiSelectMode = GridMultiSelectMode.CellSelect;
15、如何讓各列頭禁止移動?
gridView1.OptionsCustomization.AllowColumnMoving = false;
16、如何讓各列頭禁止排序?
gridView1.OptionsCustomization.AllowSort = false;
17、如何禁止各列頭改變列寬?
gridView1.OptionsCustomization.AllowColumnResizing = false;
18、如何凍結列
this.kqno(列名).Fixed = DevExpress.XtraGrid.Columns.FixedStyle.Left;
19、設定時間為年月日時分秒(yyyy-MM-dd HH:mm:ss)
/// <summary>
/// 將日期控制元件設定為yyyy-MM-dd HH:mm:ss型別
/// </summary>
/// <param name="control"></param>
protected void SetDateEdit(Control control)
{
if (control is DateEdit)
{
DateEdit dt = control as DateEdit;
dt.Properties.MinValue = new DateTime(1900, 1, 1);
dt.Properties.DisplayFormat.FormatString = "yyyy-MM-dd HH:mm:ss";
dt.Properties.DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
dt.Properties.EditFormat.FormatString = "yyyy-MM-dd HH:mm:ss";
dt.Properties.EditFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
dt.Properties.Mask.EditMask = "yyyy-MM-dd HH:mm:ss";
dt.Properties.Mask.UseMaskAsDisplayFormat = true;
}
}
20、分組顯示
OptionsView>OptionsBehavior>AutoExpandAllGroups = True
選擇要分組的列,將GroupIndex屬性設定為0
21、資料載入延時彈框
//開啟彈框
public void ShowWait()
{
SplashScreenManager.ShowForm(this, typeof(FrmWaitForm), false, false, false);
SetWaitCaption("請稍候");
SetWaitDescription("載入中...");
}
//關閉彈框
public void ShowWait(string des)
{
SplashScreenManager.ShowForm(this, typeof(FrmWaitForm), false, false, false);
SetWaitCaption("請稍候");
SetWaitDescription(des);
}
22、設定多表頭用如下表格類
BandedGridView 或者 AdvBandedGridView
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、列設定正規表示式
this.textItem.Mask.EditMask = "([0-9]\\d*(\\.\\d*[0-9])?)";
this.textItem.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.RegEx;
/// <summary>
/// 設定控制元件為數字格式,可提供正則
/// </summary>
/// <param name="textEdit"></param>
/// <param name="regx"></param>
/// <param name="far"></param>
public static void SetNumber(TextEdit textEdit, string regx)
{
textEdit.Properties.DisplayFormat.FormatString = regx;
textEdit.Properties.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
textEdit.Properties.EditFormat.FormatString = regx;
textEdit.Properties.EditFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
textEdit.Properties.Mask.EditMask = regx;
textEdit.Properties.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.Numeric;
textEdit.Properties.Mask.UseMaskAsDisplayFormat = true;
}
25.設定底部
public static void showFooterSum(BindingSource bdMain, GridView grdView, string updversionField = "updversion") {
if (!(bdMain.DataSource is DataTable)) {
return;
}
if (grdView == null) throw new Exception("請檢查GridView傳入值是否為null");
DataTable dtMain = (DataTable)bdMain.DataSource;
grdView.OptionsView.ShowFooter = dtMain.Columns.Count > 0;
int iCount = 0;
foreach (GridColumn gridColumn in grdView.Columns) {
DataColumn dataColumn = dtMain.Columns[gridColumn.FieldName];
if (dataColumn == null) {
continue;
}
if (gridColumn.ColumnEdit != null && gridColumn.ColumnEdit is RepositoryItemCheckEdit) {
var ri = ((RepositoryItemCheckEdit)gridColumn.ColumnEdit);
if (dataColumn.DataType == typeof(int)) {
ri.ValueChecked = (int)1;
ri.ValueUnchecked = (int)0;
} else if(dataColumn.DataType == typeof(long)){
ri.ValueChecked = (long)1;
ri.ValueUnchecked = (long)0;
} else if (dataColumn.DataType == typeof(double)) {
ri.ValueChecked = 1D;
ri.ValueUnchecked = 0D;
}
continue;
}
if (!gridColumn.Visible)
continue;
if (dataColumn.DataType == typeof(DateTime) && gridColumn.Visible) {
if (gridColumn.DisplayFormat.FormatString.Trim().Length == 0) {
gridColumn.DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
gridColumn.DisplayFormat.FormatString = "yyyy-MM-dd HH:mm:ss";
}
}
if (iCount == 0) {
gridColumn.SummaryItem.SummaryType = SummaryItemType.Count;
gridColumn.SummaryItem.DisplayFormat = "總數={0}";
iCount++;
continue;
}
iCount++;
if (updversionField.Equals(gridColumn.FieldName)) {
continue;
}
bool bNumber = dataColumn.DataType == typeof(double) || dataColumn.DataType == typeof(int);
bool bColumn = gridColumn.ColumnType == typeof(double) || gridColumn.ColumnType == typeof(int);
if (bNumber && gridColumn.Visible && bColumn) {
if (gridColumn.SummaryItem.SummaryType == SummaryItemType.None) {
gridColumn.SummaryItem.SummaryType = SummaryItemType.Sum;
gridColumn.SummaryItem.DisplayFormat = "{0:0.##}";
}
}
}
}
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、設定選中顏色高亮顯示
gridView.FocusedRowHandle = gridView.LocateByValue(0, col_custid, pc_cusname.EditValue);
gridView.ClearSelection();
gridView.SelectRow(gridView.FocusedRowHandle);
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; // 使能 // 和和上面繫結 同時使用有效
30、過濾表格資料
/// <summary>
/// 過濾資料
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btn_filter_Click(object sender, EventArgs e)
{
this.gridView.OptionsView.ShowFilterPanelMode = DevExpress.XtraGrid.Views.Base.ShowFilterPanelMode.Never;
this.gridView.ActiveFilterCriteria = BulidFilterCriteria();
}
private CriteriaOperator BulidFilterCriteria()
{
CriteriaOperatorCollection filterCollection = new CriteriaOperatorCollection();
if (!string.IsNullOrEmpty(this.pc_cusname.Text.Trim()))
{
filterCollection.Add(new BinaryOperator() {
LeftOperand = new OperandProperty(this.col_custname.FieldName),
OperatorType = BinaryOperatorType.Equal,
RightOperand = this.pc_cusname.Text.Trim()
});
}
return new GroupOperator(GroupOperatorType.And, filterCollection);
}
31、資料框為空的時候提示語
this.me_orderNo.Properties.NullValuePrompt = "輸入運單號,多個請以換行符分隔";
32、修改樣式,改動的行(未儲存前)顏色提示
/// <summary>
/// 修改樣式
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public static void grdView_RowStyle(object sender, RowStyleEventArgs e) {
if (!XfLocalData.DrawRowStyle) return;
GridView view = sender as GridView;
DataRow dr = view.GetDataRow(e.RowHandle);
if (dr == null) return;
if (dr.RowState != DataRowState.Unchanged) {
e.Appearance.ForeColor = Color.Red;
e.Appearance.BackColor = Color.FromArgb(245, 244, 161);
e.HighPriority = true;
}
}
33、表格匯出
//匯出
public virtual void btnExport_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
if (!BeforeExport()) return;
if (gridView == null) return;
if (gridView.DataRowCount == 0)
{
MessageDxUtil.ShowTips("沒有需要匯出的資料");
return;
}
ExportDataHelper export = new ExportDataHelper();
export.gridcontrol = grdMain;
export.gridview = gridView;
export.defaultfilename = Text + DateTime.Now.ToString("HHmmss");
export.defaultsavestylepath = Text + MenuId;
export.customizecells = GetCustomizeCells();
export.ExportData();
}
public sealed class ExportDataHelper
{
public GridControl gridcontrol { get; set; }
public GridView gridview { get; set; }
public string defaultfilename { get; set; }
public string defaultsavestylepath { get; set; }
public List<CustomizeCell> customizecells { get; set; }
public void ExportData()
{
if (gridcontrol == null) throw new Exception("請傳入匯出的GridControl");
if (gridview == null) throw new Exception("請傳入匯出的GridView");
using (FrmExportData frm = new FrmExportData(gridcontrol, gridview, RegexHelper.RegexFileName(defaultfilename), RegexHelper.RegexFileName(defaultsavestylepath)))
{
frm._customizecells = customizecells;
frm.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
frm.Text = "資料匯出";
if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
}
}
}
}
public partial class FrmExportData : BaseForm
{
#region Fields
private GridView _gridview;
private GridControl _gridcontrol;
private string _defaultfilename = string.Empty;
private string _defaultsavestylepath = string.Empty;
private object _dataSource = new object();
private List<GridColumn> _columns = null;
private const string dirname = "CellTemplate";
private string savepath = Path.Combine(Application.StartupPath, dirname);
protected internal List<CustomizeCell> _customizecells { get; set; }
private string xmlPath
{
get { return Path.Combine(savepath, _defaultsavestylepath + ".xml"); }
}
#endregion Fields
public FrmExportData()
{
InitializeComponent();
}
internal FrmExportData(GridControl gridcontrol, GridView gridview, string defaultfilename, string defaultsavestylepath) : this()
{
_gridview = gridview;
_gridcontrol = gridcontrol;
_defaultfilename = defaultfilename;
_defaultsavestylepath = defaultsavestylepath;
_dataSource = gridcontrol.DataSource;
InitList();
LoadSetupStyle();
}
internal FrmExportData(object dataSource, List<GridColumn> columns, string defaultfilename, string defaultsavestylepath) : this()
{
_dataSource = dataSource;
_columns = columns;
_defaultfilename = defaultfilename;
_defaultsavestylepath = defaultsavestylepath;
InitList2();
LoadSetupStyle();
}
private void InitList2()
{
foreach (GridColumn item in _columns)
{
txt_left.Items.Add(item);
}
}
private void InitList()
{
GridColumnReadOnlyCollection gridviewVisibleColumns = _gridview.VisibleColumns;
if (_gridview is BandedGridView)
{
foreach (BandedGridColumn item in gridviewVisibleColumns)
{
string caption = HandMutiBand(item);
GridColumn bandcol = new GridColumn()
{
Caption = caption,
Visible = item.Visible,
FieldName = item.FieldName,
Name = item.Name,
Width = item.Width,
ColumnEdit = item.ColumnEdit,
};
txt_left.Items.Add(bandcol);
}
}
else
{
foreach (GridColumn item in gridviewVisibleColumns)
{
txt_left.Items.Add(item);
}
}
}
private string HandMutiBand(BandedGridColumn column)
{
list = new List<GridBand>();
GridBand band = column.OwnerBand;
list.Add(band);
HandBand(band);
string caption = string.Empty;
list.Reverse();
list.ForEach(p =>
{
caption += (string.IsNullOrEmpty(p.Caption) ? p.Caption : p.Caption + "|");
});
if (_gridview.OptionsView.ShowColumnHeaders)
{
return caption + column.Caption;
}
else
{
return caption.TrimEnd('|');
}
}
private List<GridBand> list = new List<GridBand>();
private void HandBand(GridBand band)
{
GridBand parentband = band.ParentBand;
if (parentband != null)
{
list.Add(parentband);
HandBand(parentband);
}
}
/// <summary>
/// 獲取已設定格式
/// </summary>
private void LoadSetupStyle()
{
CheckDir();
CheckFile(xmlPath);
XDocument doc = XDocument.Load(xmlPath);
var query = doc.Descendants("ExportStyle");
if (query.Count() > 0)
{
query.ToList().ForEach(p =>
{
cmd_style.Properties.Items.Add(p.Attribute("name").Value);
});
}
}
private void btn_right_Click(object sender, EventArgs e)
{
if (txt_left.SelectedItem == null) return;
txt_right.Items.Add(txt_left.SelectedItem);
txt_left.Items.Remove(txt_left.SelectedItem);
}
private void btn_left_Click(object sender, EventArgs e)
{
if (txt_right.SelectedItem == null) return;
txt_left.Items.Add(txt_right.SelectedItem);
txt_right.Items.Remove(txt_right.SelectedItem);
}
private void btn_allright_Click(object sender, EventArgs e)
{
if (txt_left.Items.Count == 0) return;
foreach (var item in txt_left.Items)
{
txt_right.Items.Add(item);
}
txt_left.Items.Clear();
}
private void btn_allleft_Click(object sender, EventArgs e)
{
if (txt_right.Items.Count == 0) return;
foreach (var item in txt_right.Items)
{
txt_left.Items.Add(item);
}
txt_right.Items.Clear();
}
private void btn_export_Click(object sender, EventArgs e)
{
if (txt_right.Items.Count == 0) return;
foreach (GridColumn item in txt_right.Items)
{
GridColumn cl = new GridColumn();
//cl = item;
cl.Name = item.Name;
cl.Caption = item.Caption.Replace("</br>","");
cl.FieldName = item.FieldName;
cl.Width = item.Width;
cl.OptionsColumn.ReadOnly = true;
cl.Visible = true;
cl.DisplayFormat.FormatType = item.DisplayFormat.FormatType;
cl.DisplayFormat.FormatString = item.DisplayFormat.FormatString;
cl.SummaryItem.SummaryType = _gridview.Columns[item.FieldName].SummaryItem.SummaryType;
if (item.ColumnEdit != null)
{
RepositoryItem ri = item.ColumnEdit;
ri.ExportMode = item.ColumnEdit.GetType() == typeof(RepositoryItemCheckEdit) ? ExportMode.Value : ExportMode.DisplayText;
if (item.ColumnEdit.GetType() != typeof(RepositoryItemTextEdit))
{
ri.ExportMode = ExportMode.DisplayText;
cl.ColumnEdit = ri;
}
}
gv.Columns.Add(cl);
}
gc.DataSource = _dataSource;
int rowCount = gv.RowCount;
if (rowCount < 1)
{
MessageDxUtil.ShowTips("沒有需要匯出的資料!");
return;
}
else
{
try
{
ExportSetting();
SaveFileDialog saveFileDialog = new SaveFileDialog();
int xlstype = 0;
if (gv.DataRowCount >= 65535)
{
saveFileDialog.Filter = "Execl 檔案(*.xlsx) | *.xlsx";
}
else
{
xlstype = 1;
saveFileDialog.Filter = "Execl 檔案(*.xls) | *.xls | Execl 檔案(*.xlsx) | *.xlsx";
}
saveFileDialog.FileName = _defaultfilename;
if (saveFileDialog.ShowDialog() != DialogResult.OK)
{
return;
}
else
{
string filename = saveFileDialog.FileName;
saveFileDialog.AddExtension = true;
switch (xlstype)
{
case 0:
ExportXlsx(filename);
break;
case 1:
if (saveFileDialog.FilterIndex == 1)
{
ExportXls(filename);
}
else
{
ExportXlsx(filename);
}
break;
}
//if (MessageDxUtil.ShowYesNoAndTips(string.Format("資料內容成功輸出於{0},是否立即開啟檔案?", filename)) == DialogResult.Yes)
//{
try
{
System.Diagnostics.Process.Start(filename);
}
catch (Exception)
{
MessageDxUtil.ShowTips("未找到開啟Excel檔案的應用");
}
finally
{
DialogResult = DialogResult.OK;
}
//}
//else
//{
// DialogResult = DialogResult.OK;
//}
}
}
catch (Exception ex)
{
MessageDxUtil.ShowTips(string.Format("資料輸出失敗!\r\n{0}", ex.InnerException.Message));
}
finally
{
gc.DataSource = null;
}
}
}
private void ExportXls(string filename)
{
XlsExportOptionsEx optionxls = new XlsExportOptionsEx(TextExportMode.Text);
//optionxls.CustomizeCell += optionxls_CustomizeCell;
optionxls.AllowSortingAndFiltering = DevExpress.Utils.DefaultBoolean.False;
optionxls.AllowFixedColumnHeaderPanel=DevExpress.Utils.DefaultBoolean.False;
optionxls.AllowLookupValues = DevExpress.Utils.DefaultBoolean.False;
optionxls.ExportType = ExportType.DataAware;
optionxls.CustomizeCell += option_CustomizeCell;
gc.ExportToXls(filename, optionxls);
}
private void ExportXlsx(string filename)
{
XlsxExportOptionsEx optionxlsx = new XlsxExportOptionsEx(TextExportMode.Text);
//optionxlsx.CustomizeCell += optionxls_CustomizeCell;
optionxlsx.AllowSortingAndFiltering = DevExpress.Utils.DefaultBoolean.False;
optionxlsx.AllowFixedColumnHeaderPanel = DevExpress.Utils.DefaultBoolean.False;
optionxlsx.AllowLookupValues = DevExpress.Utils.DefaultBoolean.False;
optionxlsx.ExportType = ExportType.DataAware;
optionxlsx.CustomizeCell += option_CustomizeCell;
gc.ExportToXlsx(filename, optionxlsx);
}
private void optionxls_CustomizeCell(CustomizeCellEventArgs e) {
Double val;
if (Double.TryParse(e.Value.ToString(), out val) == false) {
return;
}
e.Formatting.FormatType = DevExpress.Utils.FormatType.Numeric;
if (val == Math.Floor(val)) {
e.Formatting.FormatString = "n0";
} else {
e.Formatting.FormatString = "n2";
}
e.Handled = true;
}
private void option_CustomizeCell(CustomizeCellEventArgs e)
{
if (_customizecells == null || _customizecells.Count == 0)
return;
var query = _customizecells.FirstOrDefault(p => e.ColumnFieldName == p.column.FieldName);
if (query != null)
{
string value = DataTypeUtil.ConvertToString(e.Value);
if (value == query.column.Caption)
{
return;
}
value = DataTypeUtil.ConvertToString(gv.GetRowCellValue(e.RowHandle, gv.Columns[e.ColumnFieldName]));
DataTable table = new DataTable();
DataRow datarow = gv.GetDataRow(e.RowHandle);
string primary = DataTypeUtil.ConvertToString(datarow[query.primarykey]);
DataRow[] rows = null;
switch (query.changetype)
{
case ChangeType.EMP:
table = CacheBasicInfo.GetCacheEmp(primary);
rows = table.Select(string.Format("empid='{0}'", value));
if (rows.Length > 0)
e.Value = rows[0]["empname"];
break;
case ChangeType.CUTS:
table = CacheBasicInfo.GetCacheCust(primary);
rows = table.Select(string.Format("custid='{0}'", value));
if (rows.Length > 0)
e.Value = rows[0]["custname"];
break;
case ChangeType.CONDT:
table = CacheBasicInfo.GetCacheContdept(primary);
rows = table.Select(string.Format("deptid='{0}'", value));
if (rows.Length > 0)
e.Value = rows[0]["deptname"];
break;
}
//e.Handled = true;
}
Double val = 0;
if (Double.TryParse(e.Value.ToString(), out val) == false) {
return;
}
e.Formatting.FormatType = DevExpress.Utils.FormatType.Numeric;
if (val == Math.Floor(val)) {
e.Formatting.FormatString = "n0";
} else {
var valstr = val.ToString();
if (valstr.IndexOf(".") > -1) {
if (valstr.Substring(valstr.IndexOf(".")).Length == 2) {
e.Formatting.FormatString = "n1";
} else {
e.Formatting.FormatString = "n2";
}
}
}
e.Handled = true;
}
private void ExportSetting()
{
gv.OptionsPrint.PrintHorzLines = chk_showline.Checked;
gv.OptionsPrint.PrintVertLines = chk_showline.Checked;
if (chk_autowidth.Checked)
{
gv.OptionsPrint.AutoWidth = false;
gv.BestFitColumns();
}
gv.OptionsPrint.PrintHeader = chk_head.Checked;
gv.OptionsView.ShowFooter = chk_foot.Checked;
gv.OptionsPrint.PrintFooter = chk_foot.Checked;
}
private void btn_close_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.OK;
}
private void btn_save_Click(object sender, EventArgs e)
{
if (txt_right.Items.Count == 0)
{
MessageDxUtil.ShowTips("未指定匯出格式,請先選擇匯出的列");
return;
}
string stylename = cmd_style.Text.Trim();
if (string.IsNullOrEmpty(stylename))
{
stylename = "格式" + DateTime.Now.ToString("HHmmss");
cmd_style.Text = stylename;
}
CheckDir();
CheckFile(xmlPath);
XDocument doc = XDocument.Load(xmlPath);
XElement xeleRoot = doc.Root;
var query = doc.Descendants("ExportStyle").Where(p => p.Attribute("name").Value == stylename);
if (query.Count() > 0)
{
query.ToList().ForEach(p =>
{
p.Remove();
});
}
XElement xe = new XElement("ExportStyle", new XAttribute("name", stylename));
foreach (GridColumn item in txt_right.Items)
{
xe.Add(new XElement("GridColumn", new XAttribute("Caption", item.Caption), new XAttribute("FieldName", item.FieldName), new XAttribute("Name", item.Name)));
}
xeleRoot.Add(xe);
doc.Save(xmlPath);
MessageDxUtil.ShowTips("儲存成功");
cmd_style.Properties.Items.Add(stylename);
}
private void btn_del_Click(object sender, EventArgs e)
{
string stylename = cmd_style.Text.Trim();
if (string.IsNullOrEmpty(stylename)) return;
CheckDir();
CheckFile(xmlPath);
XDocument doc = XDocument.Load(xmlPath);
var query = doc.Descendants("ExportStyle").Where(p => p.Attribute("name").Value == stylename);
if (query.Count() > 0)
{
query.ToList().ForEach(p =>
{
p.Remove();
});
}
doc.Save(xmlPath);
MessageDxUtil.ShowTips("刪除成功");
cmd_style.Text = "";
cmd_style.Properties.Items.Remove(stylename);
txt_left.Items.Clear();
txt_right.Items.Clear();
InitList();
}
private void cmd_style_SelectedValueChanged(object sender, EventArgs e)
{
txt_left.Items.Clear();
txt_right.Items.Clear();
InitList();
ComboBoxEdit cmd = sender as ComboBoxEdit;
string stylename = DataTypeUtil.ConvertToString(cmd.EditValue);
XDocument doc = XDocument.Load(xmlPath);
XElement query = doc.Descendants("ExportStyle").Where(p => p.Attribute("name").Value == stylename).FirstOrDefault();
if (query != null)
{
var eles = query.Elements().ToList();
var collection = txt_left.Items;
eles.ForEach(p =>
{
string Caption = p.Attribute("Caption").Value;
string FieldName = p.Attribute("FieldName").Value;
string Name = p.Attribute("Name").Value;
foreach (GridColumn item in collection)
{
if (item.Caption == Caption && item.FieldName == FieldName && item.Name == Name)
{
txt_right.Items.Add(item);
txt_left.Items.Remove(item);
return;
}
}
});
}
}
#region 輔助方法
/// <summary>
/// 檢查資料夾路徑
/// </summary>
private void CheckDir()
{
if (!Directory.Exists(savepath))
{
Directory.CreateDirectory(savepath);
}
}
/// <summary>
/// 檢查檔案路徑
/// </summary>
/// <param name="path"></param>
private void CheckFile(string path)
{
if (!File.Exists(path))
{
FileStream fs = File.Create(path);
fs.Flush();
fs.Close();
WriteXmlToFile(path, "<ExportStyles></ExportStyles>");
}
}
public void WriteXmlToFile(string path, string context)
{
StreamWriter sw = null;
FileStream fs = null;
try
{
fs = new FileStream(path, FileMode.Create);
sw = new StreamWriter(fs);
sw.Write(context); //Save content
}
catch
{
throw;
}
finally
{
sw.Flush();
sw.Close();
fs.Close();
}
}
#endregion 輔助方法
private void txt_left_DoubleClick(object sender, EventArgs e)
{
if (e is MouseEventArgs)
{
MouseEventArgs args = e as MouseEventArgs;
int index = txt_left.IndexFromPoint(args.Location);
if (index != ListBox.NoMatches)
{
var selecteditem = txt_left.Items[index];
txt_right.Items.Add(selecteditem);
txt_left.Items.Remove(selecteditem);
}
}
}
private void txt_right_DoubleClick(object sender, EventArgs e)
{
if (e is MouseEventArgs)
{
MouseEventArgs args = e as MouseEventArgs;
int index = txt_right.IndexFromPoint(args.Location);
if (index != ListBox.NoMatches)
{
var selecteditem = txt_right.Items[index];
txt_left.Items.Add(selecteditem);
txt_right.Items.Remove(selecteditem);
}
}
}
private void ExportByNPOI()
{
bool result = false;
IWorkbook workbook = null;
FileStream fs = null;
IRow row = null;
ISheet sheet = null;
ICell cell = null;
int rowCount = _gridview.DataRowCount;//行數
int columnCount = _gridview.Columns.Count;//列數
if (rowCount > 0 && columnCount > 0)
{
DataTable table = ((BindingSource)_gridview.DataSource).DataSource as DataTable;
SaveFileDialog saveFileDialog = new SaveFileDialog();
// 0 xls 1 xlsx
int xlstype = 0;
if (_gridview.DataRowCount > 65535)
{
saveFileDialog.Filter = "Execl 檔案(*.xlsx) | *.xlsx";
xlstype = 0;
//workbook = new XSSFWorkbook();
}
else
{
saveFileDialog.Filter = "Execl 檔案(*.xls) | *.xls | Execl 檔案(*.xlsx) | *.xlsx";
xlstype = 1;
//workbook = new HSSFWorkbook();
}
saveFileDialog.AddExtension = true;
saveFileDialog.FileName = _defaultfilename;
if (saveFileDialog.ShowDialog() != DialogResult.OK)
{
return;
}
// 0 Excel 2003 1 Excel 2007
int exceltype = 0;
if (xlstype == 0)
{
exceltype = 1;
}
else
{
if (saveFileDialog.FilterIndex == 1)
{
exceltype = 0;
}
else
{
exceltype = 1;
}
}
if (exceltype == 0)
{
workbook = new HSSFWorkbook();
}
else
{
workbook = new XSSFWorkbook();
}
sheet= workbook.CreateSheet(_defaultfilename);
//設定列頭
row = sheet.CreateRow(0);//excel第一行設為列頭
for (int i = 0; i < txt_right.Items.Count; i++)
{
GridColumn item = txt_right.Items[i] as GridColumn;
cell = row.CreateCell(i);
cell.SetCellValue(item.Caption.Replace("</br>",""));
}
for (int i = 0; i < rowCount; i++)
{
row = sheet.CreateRow(i + 1);
for (int j = 0; j < txt_right.Items.Count; j++)
{
GridColumn item = txt_right.Items[j] as GridColumn;
cell = row.CreateCell(j);
RepositoryItem columnEdit = item.ColumnEdit;
if (columnEdit!=null&&columnEdit.GetType() == typeof(RepositoryItemCheckEdit))
{
cell.SetCellValue(DataTypeUtil.ConvertToInteger32(_gridview.GetRowCellValue(i, item)));
}
else
{
Type type = table.Columns[item.FieldName].DataType;
if (type == typeof(double))
{
cell.SetCellValue(DataTypeUtil.ConvertToDouble(_gridview.GetRowCellDisplayText(i, item)));
}
else if (type == typeof(int))
{
cell.SetCellValue(DataTypeUtil.ConvertToInteger32(_gridview.GetRowCellDisplayText(i, item)));
}
else
{
cell.SetCellValue(_gridview.GetRowCellDisplayText(i, item));
}
}
}
}
using (fs = File.OpenWrite(saveFileDialog.FileName))
{
workbook.Write(fs);//向開啟的這個xls檔案中寫入資料
result = true;
}
}
}
private void simpleButton1_Click(object sender, EventArgs e)
{
ExportByNPOI();
}
}
public class CustomizeCell
{
public GridColumn column { get; set; }
public ChangeType changetype { get; set; }
public string primarykey { get; set; }
}
public enum ChangeType
{
CUTS, EMP, CONDT
}
34、設定行顏色根據條件繪色
//舉例
//普通對衝
SkinFormateRuleHelper.SetFormateRule(gridView, "drawColor2", bgc_vaildflag, Color.Orange,
string.Format("{0} = 1 and {1} = 1 and {2} <> 1",
new OperandProperty(bgc_vaildflag.FieldName),
new OperandProperty(bgc_payflag.FieldName),
new OperandProperty(bgc_banktocustflag.FieldName)));
//直返成功
SkinFormateRuleHelper.SetFormateRule(gridView, "drawColor3", bgc_vaildflag, Color.ForestGreen,
string.Format("{0} = 1 and {1} = 1 and {2} = 1",
new OperandProperty(bgc_vaildflag.FieldName),
new OperandProperty(bgc_banktocustflag.FieldName),
new OperandProperty(bgc_bankpayflag.FieldName)));
public class SkinFormateRuleHelper
{
/// <summary>
/// 給資料行設定底色
/// </summary>
/// <param name="gridView">當前列表</param>
/// <param name="gridFormatRuleName">規則名稱 要求唯一</param>
/// <param name="column">列名</param>
/// <param name="color">設定行底色</param>
/// <param name="expression">表示式</param>
/// <remarks>
/// new OperandProperty(bgc_vaildflag.FieldName) [id] = 0
/// </remarks>
public static void SetFormateRule(GridView gridView , string gridFormatRuleName, GridColumn column, Color color, string expression,Color foreColor = default(Color))
{
DevExpress.XtraGrid.GridFormatRule gridFormatRule = new DevExpress.XtraGrid.GridFormatRule();
FormatConditionRuleExpression formatConditionRuleExpression = new FormatConditionRuleExpression();
gridFormatRule.ApplyToRow = true;
gridFormatRule.Column = column;
gridFormatRule.Name = gridFormatRuleName;
formatConditionRuleExpression.Appearance.Options.UseBackColor = true;
formatConditionRuleExpression.Appearance.ForeColor = foreColor;
formatConditionRuleExpression.Appearance.BackColor = color;
formatConditionRuleExpression.Appearance.Options.HighPriority = true;
formatConditionRuleExpression.Expression = expression;
gridFormatRule.Rule = formatConditionRuleExpression;
gridView.FormatRules.Add(gridFormatRule);
}
}
35、設定下拉選單
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("SITEID", "網點編號");
dict.Add("SITENAME", "網點名稱");
dict.Add("PYCODE", "拼音碼");
dict.Add("WBCODE", "五筆碼");
ControlUtil.SetGridLookUpEditMoreColumnFilter(this, this.glue_newSendFromSite, dict, "SITEID", "SITENAME", XfLocalData.xfBaseData.dtMySite);
public static void SetGridLookUpEditMoreColumnFilter(Control form, GridLookUpEdit glpEdit, Dictionary<string, string> dicColumns, string valueMember, string displayMember, object datasource = null, bool defaultValue = false) {
if (dicColumns.Count == 0) return;
int i = 0;
foreach (KeyValuePair<string, string> item in dicColumns) {
GridColumn col = new GridColumn();
col.Caption = item.Value;
col.FieldName = item.Key;
col.Name = string.Format("col_{0}", item.Key);
col.VisibleIndex = i;
col.Width = 100;
col.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;
col.AppearanceHeader.Options.UseTextOptions = true;
glpEdit.Properties.View.Columns.Add(col);
i++;
}
glpEdit.Properties.PopupFormMinSize = new System.Drawing.Size(400, 200);
glpEdit.Properties.DataSource = datasource;
glpEdit.Properties.DisplayMember = displayMember;
glpEdit.Properties.ValueMember = valueMember;
glpEdit.Properties.AutoComplete = false;
glpEdit.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.Standard;
glpEdit.Properties.Buttons.Clear();
glpEdit.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton()});
glpEdit.Properties.NullText = null;
glpEdit.Properties.ImmediatePopup = true;
glpEdit.Properties.PopupFilterMode = PopupFilterMode.Contains;
glpEdit.Properties.AllowNullInput = DefaultBoolean.True;
glpEdit.Properties.View.IndicatorWidth = 50;
glpEdit.Properties.View.CustomDrawRowIndicator += (sender, e) => {
e.Appearance.TextOptions.HAlignment = HorzAlignment.Center;
if (e.Info.IsRowIndicator && e.RowHandle > -1) {
e.Info.DisplayText = (e.RowHandle + 1).ToString();
}
};
if (defaultValue) {
if (glpEdit.Properties.DataSource != null)
glpEdit.EditValue = glpEdit.Properties.GetKeyValue(0);
}
glpEdit.EditValueChanging += (sender, e) => {
if (form.IsDisposed) {
return;
}
if (form.Parent != null) {
if (!form.Parent.IsHandleCreated) {
return;
}
}
form.BeginInvoke(new MethodInvoker(() => {
GridLookUpEdit edit = sender as GridLookUpEdit;
GridView view = edit.Properties.View as GridView;
if (view.VisibleColumns.Count == 0) return;
List<CriteriaOperator> columnsOperators = new List<CriteriaOperator>();
foreach (GridColumn col in view.VisibleColumns) {
if (col.Visible && col.ColumnType == typeof(string))
columnsOperators.Add(new FunctionOperator(FunctionOperatorType.Contains,
new OperandProperty(col.FieldName),
new OperandValue(edit.AutoSearchText)));
}
if (columnsOperators.Count > 0) {
//獲取GriView私有變數
FieldInfo extraFilter = view.GetType().GetField("extraFilter", BindingFlags.NonPublic | BindingFlags.Instance);
string filterCondition = new GroupOperator(GroupOperatorType.Or, columnsOperators).ToString();
extraFilter.SetValue(view, filterCondition);
//獲取GriView中處理列過濾的私有方法
MethodInfo ApplyColumnsFilterEx = view.GetType().GetMethod("ApplyColumnsFilterEx", BindingFlags.NonPublic | BindingFlags.Instance);
ApplyColumnsFilterEx.Invoke(view, null);
}
}
));
};
glpEdit.KeyUp += (sender, e) => {
if (e.KeyCode == Keys.Delete || e.KeyCode == Keys.Back) {
if (string.IsNullOrEmpty(glpEdit.Text)) {
glpEdit.ResetText();
glpEdit.EditValue = null;
}
}
if (e.KeyCode == Keys.Escape) {
glpEdit.Text = null;
glpEdit.ResetText();
glpEdit.EditValue = null;
}
};
}
- 最後附上一個學習的demo與大家共勉,地址:https://download.csdn.net/download/supermrliu/10990116
- 分享到這裡就結束了,以上就是我的一些心得和體會,大家有什麼不懂需要討論的可以給我留言一起討論學習,共同進步,謝謝!
相關文章
- DevExpress控制元件學習總結 zdevExpress控制元件
- DevExpress GridControl使用(轉)devExpress
- 使用DevExpress匯出GridControl控制元件資料到excel檔案devExpress控制元件Excel
- Devexpress 控制元件學習記錄(一:BarManager 控制元件、XtraTabbedMdiManager 控制元件)devExpress控制元件
- C#反射機制學習總結C#反射
- 【C#學習之辨析小總結】C#
- .NET的C# 學習經驗總結C#
- C#程式設計學習(04):基本操作學習總結C#程式設計
- GridView學習View
- DevExpress GridView 新增和設定右鍵選單devExpressView
- C# Chart控制元件的使用總結C#控制元件
- c# 練習總結C#
- DevExpress GridView匯入匯出ExceldevExpressViewExcel
- 學習總結
- DevExpress GridView 列標題點選事件devExpressView事件
- DevExpress中獲取GridControl排序之後的ListdevExpress排序
- 【原】為DevExpress的ChartControl新增Y軸控制 和 GridControl中指定列新增超級連結devExpress
- 自定義控制元件總結和思考控制元件
- mysqlimport學習總結MySqlImport
- Maven學習總結Maven
- MyBatis 學習總結MyBatis
- awk 學習總結
- JNI 學習總結
- tkinter學習總結
- SVG學習總結SVG
- vue學習總結Vue
- WorkFlow學習總結
- HTML學習總結HTML
- Mybatis學習總結MyBatis
- Kafka 總結學習Kafka
- Typescript學習總結TypeScript
- 【TS】學習總結
- lua 學習總結
- vue 學習總結Vue
- HSF學習總結
- ElasticSearch 學習總結Elasticsearch
- BOM學習總結
- JavaWeb學習總結JavaWeb