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;
            
/// 
/// 显示行号
/// 
/// 
/// 
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();
    }
}

C# DevExpress控件Gridview和GridControl学习总结_第1张图片
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)

   /// 
   /// 将日期控件设置为yyyy-MM-dd HH:mm:ss类型
   /// 
   /// 
   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;
/// 
/// 设置控件为数字格式,可提供正则
/// 
/// 
/// 
/// 
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.##}";
       }
   }
}
}

C# DevExpress控件Gridview和GridControl学习总结_第2张图片

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、过滤表格数据

/// 
/// 过滤数据
/// 
/// 
/// 
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 = "输入运单号,多个请以换行符分隔";

C# DevExpress控件Gridview和GridControl学习总结_第3张图片32、修改样式,改动的行(未保存前)颜色提示

/// 
/// 修改样式
/// 
/// 
/// 
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 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 _columns = null;
    private const string dirname = "CellTemplate";
    private string savepath = Path.Combine(Application.StartupPath, dirname);

    protected internal List _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 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 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 list = new List();

    private void HandBand(GridBand band)
    {
        GridBand parentband = band.ParentBand;
        if (parentband != null)
        {
            list.Add(parentband);
            HandBand(parentband);
        }
    }

    /// 
    /// 获取已设置格式
    /// 
    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("
",""); 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 辅助方法 /// /// 检查文件夹路径 /// private void CheckDir() { if (!Directory.Exists(savepath)) { Directory.CreateDirectory(savepath); } } /// /// 检查文件路径 /// /// private void CheckFile(string path) { if (!File.Exists(path)) { FileStream fs = File.Create(path); fs.Flush(); fs.Close(); WriteXmlToFile(path, ""); } } 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("
","")); } 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
{
   /// 
   ///  给数据行设置底色
   /// 
   /// 当前列表
   /// 规则名称 要求唯一
   /// 列名
   /// 设置行底色
   /// 表达式
   /// 
   /// new OperandProperty(bgc_vaildflag.FieldName) [id] = 0
   /// 
   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 dict = new Dictionary();
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 dicColumns, string valueMember, string displayMember, object datasource = null, bool defaultValue = false) {
if (dicColumns.Count == 0) return;
int i = 0;
foreach (KeyValuePair 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 columnsOperators = new List();
        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;
    }
};
}

C# DevExpress控件Gridview和GridControl学习总结_第4张图片

  • 最后附上一个学习的demo与大家共勉,地址:https://download.csdn.net/download/supermrliu/10990116
  • 分享到这里就结束了,以上就是我的一些心得和体会,大家有什么不懂需要讨论的可以给我留言一起讨论学习,共同进步,谢谢!

你可能感兴趣的:(C#)