/****************************** * 说明:多表头表格 * 创建人:龚宇超 * 创建日期:2017-12-25 * 修改人: * 修改日期: * 修改备注: * 版本:1.0.0.0 ******************************/ using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; using Lskj.Model; using DevExpress.XtraGrid; using DevExpress.XtraGrid.Views.Grid; using DevExpress.XtraGrid.Views.BandedGrid; using Lskj.Control.Model; using DevExpress.Utils; using DevExpress.Data; using DevExpress.XtraGrid.Columns; using DevExpress.XtraGrid.Views.Base; using Lskj.Data; using Lskj.Business; using DevExpress.XtraEditors.Repository; using Lskj.Business.Impl; using Lskj.Util; using System.Text.RegularExpressions; using DevExpress.XtraGrid.Views.Grid.ViewInfo; using DevExpress.XtraGrid.Menu; using DevExpress.Utils.Menu; using Lskj.Core; using System.Data.SqlClient; using DevExpress.XtraEditors; using DevExpress.Data.Filtering; using DevExpress.XtraEditors.Controls; namespace Lskj.Control { /// /// 多表头表格 /// public partial class BandedGridControlEx : GridControlEx { /// /// 创建Dictionary存储行号为Key,有效日期格式列名数组为Value /// public Dictionary> rowDateValues = new Dictionary>(); /// /// 获取模块配置 /// public ModuleModel moduleModel; /// /// Gets the grid view. /// /// The grid view. public override GridView GridView { get { return this.bandedGridView; } } /// /// 多表头 /// public BandedGridView BandedView { get { return this.bandedGridView; } } /// /// 粘贴表格数据时调用 /// public event ParseGridDataEventHandler OnParseGridDataCallBack; /// /// 数据源绑定完成触发 /// public event EventHandler OnDataSourceBindCallBack; /// /// 按初始顺序保存全部gridBand /// public List saveGridBands = new List(); /// /// 按初始顺序保存全部gridBand对应的二级列名 /// public Dictionary saveGridBandColumn = new Dictionary(); /// /// 当前选中行数组 /// private int[] SelectedRows = new int[0]; /// /// 冻结列 /// private List FrozenColumns = new List(); /// /// 滚动条位置改变回调 /// public event EventHandler OnLeftCoordCallback; /// /// 虚拟列颜色 /// public Dictionary ColorDictionary = new Dictionary(); /// /// 虚拟列关联字段 /// public string virtualPrimaryKey; /// /// 行数合计列 /// 合计xx行 列,因为默认给的在最前面插入空白表头列,按照工具顺序加载列,可能会出现有2列合计行,所以在重新创建时就把之前的清空 /// public GridColumn TotalColumn; public BandedGridControlEx() { InitializeComponent(); this.bandedGridView.CustomDrawRowIndicator += new RowIndicatorCustomDrawEventHandler(OnGridViewCustomDrawRowIndicator); this.bandedGridView.SelectionChanged += new SelectionChangedEventHandler(OnGridViewSelectionChanged); this.bandedGridView.CustomDrawCell += new RowCellCustomDrawEventHandler(OnGridViewCustomDrawCell); this.bandedGridView.CellValueChanged += new CellValueChangedEventHandler(OnGridViewCellValueChanged); this.bandedGridView.KeyDown += new KeyEventHandler(OnGridViewKeyDown); this.bandedGridView.DragObjectDrop += new DragObjectDropEventHandler(OnGridViewDragObjectDrop); this.bandedGridView.CellMerge += new CellMergeEventHandler(OnGridViewCellMerge); this.bandedGridView.CustomSummaryCalculate += new CustomSummaryEventHandler(OnGridViewSummaryCalculate); this.bandedGridView.ShowFilterPopupCheckedListBox += new FilterPopupCheckedListBoxEventHandler(OnShowFilterPopupCheckedListBox);//(修复筛选条件) this.bandedGridView.PopupMenuShowing += new DevExpress.XtraGrid.Views.Grid.PopupMenuShowingEventHandler(this.OnGridViewPopupMenuShowing); this.bandedGridView.Click += new EventHandler(OnBandedGridView_Click); this.bandedGridView.DoubleClick += new EventHandler(OnBandedGridViewDoubleClick); this.bandedGridView.CustomDrawGroupRow += new RowObjectCustomDrawEventHandler(OnGridCustomDrawGroupRow); this.bandedGridView.LeftCoordChanged += OnBandedLeftCoordChanged; this.SetGridRowHeightAndFont(); if (SystemInfo.Instance.GroupRowFontSizeDelta > 0) { this.bandedGridView.Appearance.GroupRow.FontSizeDelta = SystemInfo.Instance.GroupRowFontSizeDelta; } this.bandedGridView.EndSorting += BandedGridView_EndSorting;//排序后选中第一行 this.bandedGridView.ShowingEditor += GridView_ShowingEditor; } /// /// 说明:单元格合并 /// 创建人:王一帆 /// 创建日期: /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The sender. /// The instance containing the event data. protected void OnGridViewCellMerge(object sender, CellMergeEventArgs e) { try { GridColumn column = e.Column; GridColumnModel model = column.Tag as GridColumnModel; if (model == null) { e.Handled = true; return; } if (string.IsNullOrEmpty(model.MergeGroup)) { return; } string[] fields = model.MergeGroup.Trim(',').Split(','); for (int i = 0; i < fields.Length; i++) { int row1 = e.RowHandle1; int row2 = e.RowHandle2; string McColumn = fields[i] + "";//关联条件列 string value1 = bandedGridView.GetDataRow(row1)[McColumn].ToString(); string value2 = bandedGridView.GetDataRow(row2)[McColumn].ToString(); if (value1 != value2) { e.Handled = true; } else { e.Handled = false; } } } catch (Exception ex) { string Message = ErrorMessage.PromptErrorMessage(ex, Model.ModuleCode); MessageUtil.Show(Message, ex.Message); LogHelper.Instance.WriteError(ex); } } private string GetMergeGroupValue(GridColumnModel model, DataRow row) { if (model == null || row == null || string.IsNullOrEmpty(model.MergeGroup)) return string.Empty; string[] fields = model.MergeGroup.Trim(',').Split(','); StringBuilder groupValue = new StringBuilder(); foreach (string item in fields) { string fieldName = (item + "").Trim(); if (string.IsNullOrEmpty(fieldName) || !row.Table.Columns.Contains(fieldName)) continue; groupValue.Append(fieldName); groupValue.Append("="); groupValue.Append(row[fieldName] + ""); groupValue.Append("|"); } return groupValue.ToString(); } /// /// 说明:重写设置表格颜色 /// 创建人:王一帆 /// 创建日期:2020-09-10 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The table. public override void SetGridRowColors(DataTable table) { this.GridRowColorsTable = table; if (table != null && table.Rows.Count > 0) { DataRow rowItem = table.Select("1=1").FirstOrDefault(x => (x["condition"] + "").Contains("COLUMN_")); if (rowItem != null) { this.GridView.RowCellStyle -= new RowCellStyleEventHandler(OnGridViewRowCellStyle); this.GridView.RowCellStyle += new RowCellStyleEventHandler(OnGridViewRowCellStyle); } else { if (!SystemInfo.Instance.ConditionalStylePriority) { this.GridView.RowStyle -= new RowStyleEventHandler(OnGridViewRowStyle); this.GridView.RowStyle += new RowStyleEventHandler(OnGridViewRowStyle); } } } } /// /// 说明:设置表格行颜色 /// 创建人:龚宇超 /// 创建日期:2019-06-10 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The sender. /// The instance containing the event data. protected void OnGridViewRowStyle(object sender, RowStyleEventArgs e) { if (e.RowHandle >= 0 && this.GridRowColorsTable != null && this.GridRowColorsTable.Rows.Count > 0) { // 渲染界面数据量过多界面刷新会很慢 DataRow gridRow = this.GridView.GetDataRow(e.RowHandle); foreach (DataRow item in this.GridRowColorsTable.Rows) { //string cond = ReplaceHelper.ReplaceRowParam(gridRow, item["condition"] + ""); string cond = ReplaceHelper.ReplaceRowParamEmptyWrapQuote(gridRow, item["condition"] + ""); try { if (!string.IsNullOrWhiteSpace(cond) && ReplaceHelper.EvalCond(cond)) { GridRowColorModel model = new GridRowColorModel(item); if (!string.IsNullOrWhiteSpace(model.BackColor)) { e.Appearance.BackColor = ColorTranslator.FromHtml(model.BackColor); } if (!string.IsNullOrWhiteSpace(model.ForceColor)) { e.Appearance.ForeColor = ColorTranslator.FromHtml(model.ForceColor); } FontStyle fontStyle = FontStyle.Regular; if (model.IsBold) fontStyle |= FontStyle.Bold; if (model.IsItalic) fontStyle |= FontStyle.Italic; if (model.IsStrickOut) fontStyle |= FontStyle.Strikeout; if (model.IsUnderLine) fontStyle |= FontStyle.Underline; e.Appearance.FontStyleDelta = fontStyle; } } catch (Exception) { //LogHelper.Instance.WriteLog("GridView RowCellStyle Error. Condition:" + model.Condition + ";EvalCondtion:" + cond); } } } } /// /// 说明:设置表格单元格颜色 /// 创建人:王一帆 /// 创建日期:2020-09-10 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The source of the event. /// The instance containing the event data. /// public void OnGridViewRowCellStyle(object sender, RowCellStyleEventArgs e) { var view = sender as DevExpress.XtraGrid.Views.Grid.GridView; bool isLaterDatePresent = false; if (view.IsCellSelected(e.RowHandle, e.Column)) { return; // 如果当前单元格被选中,则不应用自定义样式 } if (e.RowHandle >= 0 && this.GridRowColorsTable != null && this.GridRowColorsTable.Rows.Count > 0) { DataRow gridRow = view.GetDataRow(e.RowHandle); // 获取行的最大日期值 DateTime? maxDateForRow = null; if (gridRow.Table.Columns.Contains("PrecomputedMaxDate")) { bool isFieldDate = DateTime.TryParse(e.Column.FieldName, out DateTime FieldDate); bool isMaxDate = DateTime.TryParse(gridRow["PrecomputedMaxDate"].ToString(), out DateTime parsedDate); if (isMaxDate && isFieldDate) { maxDateForRow = parsedDate; if (FieldDate < parsedDate) { isLaterDatePresent = true; } } else if (isFieldDate) { return; // 如果当前是日期框模式且没有定义最大值则直接跳过 } } //DateTime? maxDateForRow = GetMaxDateFromColumnNames(gridRow); foreach (DataRow item in this.GridRowColorsTable.Rows) { string condition = item["condition"] + ""; string cond = condition; // 检查是否条件字符串包含 'COLUMN_NAME' if (condition.Contains("COLUMN_NAME")) { // 解析期望的列名 string pattern = @"('{?COLUMN_NAME}'?\s*=\s*'[^']*')"; var matches = Regex.Matches(condition, pattern, RegexOptions.IgnoreCase); var results = new List(); foreach (Match match in matches) { results.Add(match.Value); } string expectedColumnName = ""; if (results.Count > 0) { expectedColumnName = results[0].Split('=').Last().Trim('\''); } if (!expectedColumnName.Equals(e.Column.Name, StringComparison.OrdinalIgnoreCase)) { continue; } } //cond = ReplaceHelper.ReplaceRowParam(gridRow, item["condition"] + "").ReplaceColumnParam(e.Column.Name, e.Column.Caption, e.CellValue + ""); cond = ReplaceHelper.ReplaceRowParamEmptyWrapQuote(gridRow, item["condition"] + "").ReplaceColumnParam(e.Column.Name, e.Column.Caption, e.CellValue + ""); try { if (!string.IsNullOrWhiteSpace(cond) && ReplaceHelper.EvalCond(cond) && (!string.IsNullOrEmpty(e.CellValue + "") || isLaterDatePresent|| SystemInfo.Instance.isBlankCellColor)) { GridRowColorModel model = new GridRowColorModel(item); if (!string.IsNullOrWhiteSpace(model.BackColor)) { e.Appearance.BackColor = ColorTranslator.FromHtml(model.BackColor); } if (!string.IsNullOrWhiteSpace(model.ForceColor)) { e.Appearance.ForeColor = ColorTranslator.FromHtml(model.ForceColor); } FontStyle fontStyle = FontStyle.Regular; if (model.IsBold) fontStyle |= FontStyle.Bold; if (model.IsItalic) fontStyle |= FontStyle.Italic; if (model.IsStrickOut) fontStyle |= FontStyle.Strikeout; if (model.IsUnderLine) fontStyle |= FontStyle.Underline; e.Appearance.FontStyleDelta = fontStyle; } } catch (Exception ex) { // 考虑增加错误日志记录 // LogHelper.Instance.WriteLog("GridView RowCellStyle Error. Condition:" + item["condition"] + "; EvalCondtion:" + cond, ex); } } } if (e.RowHandle >= 0 && this.ColorDictionary.Count > 0 && !string.IsNullOrWhiteSpace(this.virtualPrimaryKey) && bandedGridView.Columns.ColumnByName(this.virtualPrimaryKey) != null) { DataRow gridRow = view.GetDataRow(e.RowHandle); string key = gridRow[this.virtualPrimaryKey] +"^"+ e.Column.FieldName; string value; if (this.ColorDictionary.TryGetValue(key, out value)) { //DataModel.TopModuleModel.ParmaryKey e.Appearance.BackColor = ColorTranslator.FromHtml("#"+ value); } } } /// /// 解析列名是否为日期模式 /// /// /// /// private bool IsDateColumn(string fieldName, out DateTime date) { // 通过正则表达式或其他方法来解析字段名是否包含日期,并尝试解析日期 return DateTime.TryParse(fieldName, out date); // 示例,实际应根据实际字段名解析逻辑 } /// /// 获取行中最大的有效日期 /// /// /// private DateTime? GetMaxDateFromColumnNames(DataRow row) { DateTime? maxDate = null; foreach (DataColumn column in row.Table.Columns) { DateTime date; if (IsDateColumn(column.ColumnName, out date)) { if (!maxDate.HasValue || date > maxDate.Value) { if (!string.IsNullOrEmpty(row[column.ColumnName] + "")) { maxDate = date; } } } } return maxDate; } /// /// 说明:设置只读列 /// 创建人:龚宇超 /// 创建日期:2017-12-25 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The table. public override void SetReadOnlyColumns(DataTable table, string customColumKey = "") { //设置列头自动高度 this.bandedGridView.OptionsView.ColumnHeaderAutoHeight = DefaultBoolean.True; base.CustomColumKey = customColumKey; base.ColumnList.Clear(); this.bandedGridView.Bands.Clear(); this.bandedGridView.Columns.Clear(); this.AddBandColumns(table); } /// /// 说明:设置可编辑列 /// 创建人:龚宇超 /// 创建日期:2017-12-25 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The table. public override void SetEditColumns(DataTable table, string customColumKey = "") { //设置列头自动高度 this.bandedGridView.OptionsView.ColumnHeaderAutoHeight = DefaultBoolean.True; base.CustomColumKey = customColumKey; base.ColumnList.Clear(); this.bandedGridView.Bands.Clear(); this.bandedGridView.Columns.Clear(); this.AddBandColumns(table, false); } /// /// 说明: /// 创建人:龚宇超 /// 创建日期:2019-11-11 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// protected void SetGridRowHeightAndFont() { if (SystemInfo.Instance.GridRowFontSize > 0) this.bandedGridView.Appearance.Row.Font = new Font("微软雅黑", SystemInfo.Instance.GridRowFontSize); if (SystemInfo.Instance.GridRowHeight > 0) { this.bandedGridView.ColumnPanelRowHeight = this.bandedGridView.RowHeight = SystemInfo.Instance.GridRowHeight; } } /// /// 说明:是否为多表头 /// 创建人:龚宇超 /// 创建日期:2017-12-25 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// Name of the field. /// The bands. protected string HasBand(string fieldName, GridColumnModel[] bands) { foreach (GridColumnModel model in bands) { if (("|" + model.BandFields + "|").Contains("|" + fieldName + "|")) { return model.BandTitle; } } return string.Empty; } /// /// 说明:获取选中行数据 /// 创建人:龚宇超 /// 创建日期:2019-10-18 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// DataRow[]. public override DataRow[] GetViewFocusedDataRows() { int[] rows = GridView.GetSelectedRows(); DataRow[] dataRows = new DataRow[rows.Length]; for (int i = 0; i < rows.Length; i++) { dataRows[i] = GridView.GetDataRow(rows[i]); } return dataRows; } /// /// 说明: /// 创建人:龚宇超 /// 创建日期: /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// DataRow. public override DataRow GetViewFocusedDataRow() { return GridView.GetFocusedDataRow(); } /// /// 说明:添加多表头列 /// 创建人:龚宇超 /// 创建日期:2018-04-11 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The table. /// if set to true [read only]. protected void AddBandColumns(DataTable table, bool readOnly = true) { if (table == null) return; this.InitGridColumsTab = table; this.mControlList.Clear(); List bandFieldstr = new List(); string bandFields = string.Empty; foreach (DataRow item in table.Rows) { GridColumnModel model = new GridColumnModel(item); this.ColumnList.Add(model); } Dictionary gridBandEmptyDic = new Dictionary(); GridBand gridBandEmpty = new GridBand(); //this.bandedGridView.OptionsView.ColumnHeaderAutoHeight = DefaultBoolean.True; // 添加Band 列 GridColumnModel[] bandRows = this.ColumnList.Where(x => !string.IsNullOrEmpty(x.BandFields)).ToArray(); GridColumnModel[] AutobandRows = this.ColumnList.Where(x => x.FieldText.Contains("|")).ToArray(); GridColumnModel[] bandEmptyRows = null; if (this.moduleModel != null && this.moduleModel.BandSequentialMode) { bandEmptyRows = AutobandRows.Length > 0 ? this.ColumnList.Where(x => !x.FieldText.Contains("|") && x.Width > 0).ToArray() : this.ColumnList.Where(x => bandRows.Select(n => n.BandFields.Equals(x.FieldName)).Count() == 0 && x.Width > 0).ToArray(); foreach (GridColumnModel columnModel in this.ColumnList) { if (!string.IsNullOrEmpty(columnModel.BandFields)) { GridBand gridBand = new GridBand(); gridBand.Caption = columnModel.BandTitle; gridBand.AppearanceHeader.Options.UseFont = true; gridBand.AppearanceHeader.Font = new Font("宋体", 9, FontStyle.Bold); gridBand.AppearanceHeader.Options.UseTextOptions = true; gridBand.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center; if (columnModel.BandTitle.Contains("\\r\\n")) { gridBand.AppearanceHeader.Options.UseTextOptions = true; gridBand.AppearanceHeader.TextOptions.WordWrap = WordWrap.Wrap; gridBand.Caption = columnModel.BandTitle.Replace("\\r\\n", " "); gridBand.RowCount = 2; } saveGridBands.Add(gridBand); bandedGridView.Bands.AddRange(new GridBand[] { gridBand }); gridBandEmpty = new GridBand();//切换时重置空列 } else if (columnModel.FieldText.Contains("|")) { if (bandRows.Length == 0 && AutobandRows.Length > 0) { GridBand gridBand = new GridBand(); int index = columnModel.FieldText.LastIndexOf("|"); string bandTitle = columnModel.FieldText.Substring(0, index); string bandField = columnModel.FieldText.Substring(index + 1, columnModel.FieldText.Length - index - 1); if (bandFieldstr.Contains(bandTitle)) continue; bandFieldstr.Add(bandTitle); gridBand.Caption = bandTitle; gridBand.AppearanceHeader.Options.UseFont = true; gridBand.AppearanceHeader.Font = new Font("宋体", 9, FontStyle.Bold); gridBand.AppearanceHeader.Options.UseTextOptions = true; gridBand.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center; if (bandTitle.Contains("\\r\\n")) { gridBand.AppearanceHeader.Options.UseTextOptions = true; gridBand.AppearanceHeader.TextOptions.WordWrap = WordWrap.Wrap; gridBand.Caption = bandTitle.Replace("\\r\\n", " "); gridBand.RowCount = 2; } //gridBand.RowCount = 10; //gridBand.AppearanceHeader.TextOptions.WordWrap = WordWrap.Wrap; saveGridBands.Add(gridBand); bandedGridView.Bands.AddRange(new GridBand[] { gridBand }); gridBandEmpty = new GridBand();//切换时重置空列 } } else if ((AutobandRows.Length > 0 && !columnModel.FieldText.Contains("|") && columnModel.Width > 0) || (AutobandRows.Length <= 0 && bandRows.Select(n => n.BandFields.Equals(columnModel.FieldName)).Count() == 0 && columnModel.Width > 0)) { // 空白列 gridBandEmpty.Caption = ""; gridBandEmpty.AppearanceHeader.Options.UseFont = true; gridBandEmpty.AppearanceHeader.Font = new Font("宋体", 9, FontStyle.Bold); gridBandEmpty.AppearanceHeader.Options.UseTextOptions = true; gridBandEmpty.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center; if (!bandedGridView.Bands.Contains(gridBandEmpty)) { bandedGridView.Bands.Add(gridBandEmpty); } gridBandEmptyDic.Add(this.ColumnList.IndexOf(columnModel), gridBandEmpty); } } } else { foreach (GridColumnModel item in bandRows) { GridBand gridBand = new GridBand(); gridBand.Caption = item.BandTitle; gridBand.AppearanceHeader.Options.UseFont = true; gridBand.AppearanceHeader.Font = new Font("宋体", 9, FontStyle.Bold); gridBand.AppearanceHeader.Options.UseTextOptions = true; gridBand.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center; if (item.BandTitle.Contains("\\r\\n")) { gridBand.AppearanceHeader.Options.UseTextOptions = true; gridBand.AppearanceHeader.TextOptions.WordWrap = WordWrap.Wrap; gridBand.Caption = item.BandTitle.Replace("\\r\\n", " "); gridBand.RowCount = 2; } saveGridBands.Add(gridBand); bandedGridView.Bands.AddRange(new GridBand[] { gridBand }); bandFields += "|" + item.BandFields; } if (bandRows.Length == 0 && AutobandRows.Length > 0) { foreach (GridColumnModel item in AutobandRows) { GridBand gridBand = new GridBand(); int index = item.FieldText.LastIndexOf("|"); string bandTitle = item.FieldText.Substring(0, index); string bandField = item.FieldText.Substring(index + 1, item.FieldText.Length - index - 1); if (bandFieldstr.Contains(bandTitle)) continue; bandFieldstr.Add(bandTitle); gridBand.Caption = bandTitle; gridBand.AppearanceHeader.Options.UseFont = true; gridBand.AppearanceHeader.Font = new Font("宋体", 9, FontStyle.Bold); gridBand.AppearanceHeader.Options.UseTextOptions = true; gridBand.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center; if (bandTitle.Contains("\\r\\n")) { gridBand.AppearanceHeader.Options.UseTextOptions = true; gridBand.AppearanceHeader.TextOptions.WordWrap = WordWrap.Wrap; gridBand.Caption = bandTitle.Replace("\\r\\n", " "); gridBand.RowCount = 2; } //gridBand.RowCount = 10; //gridBand.AppearanceHeader.TextOptions.WordWrap = WordWrap.Wrap; saveGridBands.Add(gridBand); bandedGridView.Bands.AddRange(new GridBand[] { gridBand }); bandFields += "|" + bandField; } } bandFields = bandFields + "|"; // 检查是否包含空白列 bandEmptyRows = AutobandRows.Length > 0 ? this.ColumnList.Where(x => !x.FieldText.Contains("|") && x.Width > 0).ToArray() : this.ColumnList.Where(x => !bandFields.Contains("|" + x.FieldName + "|") && x.Width > 0).ToArray(); if (bandEmptyRows != null && bandEmptyRows.Length > 0) { // 空白列 gridBandEmpty.Caption = ""; gridBandEmpty.AppearanceHeader.Options.UseFont = true; gridBandEmpty.AppearanceHeader.Font = new Font("宋体", 9, FontStyle.Bold); gridBandEmpty.AppearanceHeader.Options.UseTextOptions = true; gridBandEmpty.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center; if (this.moduleModel != null && moduleModel.BandedAddToEnd) { bandedGridView.Bands.Add(gridBandEmpty); } else { bandedGridView.Bands.Insert(0, gridBandEmpty); } } } // 创建列 for (int i = 0; i < this.ColumnList.Count; i++) { GridColumnModel model = this.ColumnList[i]; //if (model.Width == 0 || !model.Visible) continue; int startIndex = model.FieldText.Contains("|") ? model.FieldText.LastIndexOf("|") : 0; string FieldText = startIndex > 0 ? model.FieldText.Substring(startIndex + 1, model.FieldText.Length - startIndex - 1) : model.FieldText; BandedGridColumn gridColumn = new BandedGridColumn(); gridColumn.OptionsFilter.AutoFilterCondition = AutoFilterCondition.Contains; string bandTitle = startIndex > 0 ? model.FieldText.Substring(0, startIndex) : HasBand(model.FieldName, bandRows); if (!string.IsNullOrEmpty(bandTitle)) { // 绑定了多表头显示 GridBand gridBand = this.bandedGridView.Bands.Cast().FirstOrDefault(x => x.Caption == bandTitle); if (gridBand != null) { gridBand.Columns.Add(gridColumn); if (saveGridBandColumn.ContainsKey(gridBand)) { saveGridBandColumn[gridBand] = saveGridBandColumn[gridBand] + model.FieldName + "^"; } else { saveGridBandColumn.Add(gridBand, model.FieldName + "^"); } } bandedGridView.Columns.Add(gridColumn); } else { // 未绑定多表头则直接显示 if (bandEmptyRows != null && bandEmptyRows.Contains(model)) { if (this.moduleModel != null && this.moduleModel.BandSequentialMode) { gridBandEmptyDic[this.ColumnList.IndexOf(model)].Columns.Add(gridColumn); } else { gridBandEmpty.Columns.Add(gridColumn); } } bandedGridView.Columns.Add(gridColumn); } gridColumn.OptionsColumn.AllowMerge = model.CanMerge ? DefaultBoolean.True : DefaultBoolean.False; if (model != null && model.CanMerge) bandedGridView.OptionsView.AllowCellMerge = true;//若有合并列则设置表合并,合并后无法多选 gridColumn.FieldName = model.FieldName; gridColumn.Name = model.FieldName; gridColumn.VisibleIndex = i; gridColumn.Caption = FieldText; gridColumn.Width = model.Width; gridColumn.Visible = model.Visible; gridColumn.OptionsColumn.AllowEdit = !readOnly && model.Edit; gridColumn.Tag = model; gridColumn.OptionsFilter.FilterPopupMode = FilterPopupMode.CheckedList; gridColumn.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center; if (model.DataAlignment > 0) { gridColumn.AppearanceCell.Options.UseTextOptions = true; gridColumn.AppearanceCell.TextOptions.HAlignment = model.DataAlignment == 1 ? DevExpress.Utils.HorzAlignment.Center : DevExpress.Utils.HorzAlignment.Far; } if (!string.IsNullOrWhiteSpace(model.TitleColor)) { gridColumn.AppearanceHeader.Options.UseForeColor = true; gridColumn.AppearanceHeader.ForeColor = ColorTranslator.FromHtml(model.TitleColor); } if (EnabledChangeColor) { if (!model.Edit) { gridColumn.AppearanceHeader.Options.UseForeColor = true; gridColumn.AppearanceHeader.ForeColor = ColorTranslator.FromHtml(HeaderColor); } else if (model.CanNull) { gridColumn.AppearanceHeader.Options.UseForeColor = true; gridColumn.AppearanceHeader.ForeColor = RequiredForceColor; } } this.SetColumnFormat(gridColumn, model); this.SetColumnSumming(gridColumn, model); this.InitEditColumns(gridColumn, model); if (model.RepeatedVerification) { this.RepeatedVerificationNames.Add(model.FieldName); } //工具中设置的冻结列 if (model.FrozenFlag) { //gridColumn.Fixed = FixedStyle.Left; //FixLeftItemClick(gridColumn, new EventArgs()); FrozenColumns.Add(gridColumn); } if (!string.IsNullOrWhiteSpace(model.PromptText)) { PromptMessage.Add(model.FieldName, model.PromptText); } if (!string.IsNullOrWhiteSpace(model.ColumnAnnotation)) { gridColumn.ToolTip = model.ColumnAnnotation; } } // 加载数据源 //BindDataSource(); this.SetCustomColumns();//加载多表头自定义列 //多表头冻结 foreach (BandedGridColumn item in FrozenColumns) { FixLeftItemClick(item, new EventArgs()); } // 延迟加载数据源 this.mLoading = false; this.mTimer.Tick += new EventHandler(mTimerTick); this.mTimer.Start(); } /// /// 说明:设置自定义列 /// 创建人:龚宇超 /// 创建日期:2018-02-01 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// protected virtual void SetCustomColumns(bool isInit = true) { if (string.IsNullOrEmpty(this.CustomColumKey) || !BaseImpl.HasExistsTable(ResourceKeys.SettingTableName)) return; if (!BaseImpl.HasExistsColumn(ResourceKeys.SettingTableName, "FieldText")) { BaseImpl.ExecSqlValue("alter table " + ResourceKeys.SettingTableName + " add FieldText varchar(100)"); } DataTable customTable = this.bandedGridView.GetCustomColumnByDatabase(this.CustomColumKey); if (customTable != null && customTable.Rows.Count > 0) { int MaxIndex = customTable.Columns.Count; foreach (DataRow rowItem in customTable.Rows) { string fieldName = rowItem["fieldName"] + ""; string FieldText = rowItem["FieldText"] + ""; int fieldWidth = Convert.ToInt32(rowItem["fieldWidth"]); int index = Convert.ToInt32(rowItem["orderid"]); bool visible = "1".Equals(rowItem["isVisible"] + "") && fieldWidth > 0; bool isFix = "True".Equals(rowItem["IfFixColumn"] + "", StringComparison.OrdinalIgnoreCase); string FilterInfo = rowItem.Table.Columns.Contains("FilterInfo") ? rowItem["FilterInfo"] + "" : "";//列筛选条件 GridColumnModel column = this.ColumnList.Find(x => x.FieldName == fieldName); BandedGridColumn gridColumn = this.bandedGridView.Columns.ColumnByName(fieldName); if (column != null && !string.IsNullOrEmpty(fieldName) && gridColumn != null && gridColumn.Visible && gridColumn.Width > 0) { BandedGridColumn colObj = this.bandedGridView.Columns[fieldName]; GridBand gridBand = colObj.OwnerBand; if (index >= 0 && index <= this.bandedGridView.Columns.Count - 1) { this.bandedGridView.Columns.Remove(colObj); this.bandedGridView.Columns.Insert(index, colObj); } colObj.OwnerBand = gridBand; colObj.VisibleIndex = index; colObj.Width = fieldWidth; colObj.Visible = visible; if (!string.IsNullOrWhiteSpace(FilterInfo)) colObj.FilterInfo = new ColumnFilterInfo(FilterInfo); if (FieldText.Contains("|") && isFix) { FixLeftItemClick(colObj, new EventArgs()); } else { colObj.OwnerBand.Fixed = isFix ? FixedStyle.Left : FixedStyle.None; } } } //是否显示筛选器行 if (customTable.Columns.Contains("DisplayFiltering") && "1".Equals(customTable.Rows[0]["DisplayFiltering"] + "")) this.bandedGridView.OptionsView.ShowAutoFilterRow = true; //分组序号 if (customTable.Columns.Contains("GroupIndex")) { DataRow[] dataRows = customTable.Select("GroupIndex>-1"); for (int i = 0; i < dataRows.Length; i++) { DataRow row = dataRows.Cast().FirstOrDefault(x => Convert.ToInt32(x["GroupIndex"] + "") == i); if (row != null) { string fieldName = row["fieldName"] + ""; int GroupIndex = row.Table.Columns.Contains("GroupIndex") ? Convert.ToInt32(row["GroupIndex"] + "") : -1; GridColumnModel column = this.ColumnList.Find(x => x.FieldName == fieldName); BandedGridColumn gridColumn = this.bandedGridView.Columns.ColumnByName(fieldName); if (column != null && !string.IsNullOrEmpty(fieldName) && gridColumn != null && gridColumn.Visible && gridColumn.Width > 0) { BandedGridColumn colObj = this.bandedGridView.Columns[fieldName]; if (GroupIndex > -1) { colObj.GroupIndex = GroupIndex; this.bandedGridView.OptionsView.ShowGroupPanel = true; } } } } // 隐藏分组面板 this.bandedGridView.OptionsView.ShowGroupPanel = false; // 展开所有分组 this.bandedGridView.OptionsBehavior.AutoExpandAllGroups = true;//展开所有分组 } foreach (BandedGridColumn col in this.bandedGridView.Columns) { DataRow a = customTable.Rows.Cast().FirstOrDefault(x => col.Name.Equals(x["fieldName"] + "", StringComparison.OrdinalIgnoreCase)); if (a == null) { bool visible = col.Visible;//获取设置VisibleIndex之前列的状态 col.VisibleIndex = MaxIndex; MaxIndex += 1; col.Visible = visible; } } } if (!isInit) { // 非初始化,假如未配置则初始化到系统配置 for (int i = 0; i < this.ColumnList.Count; i++) { GridColumnModel column = this.ColumnList[i]; if (this.bandedGridView.Columns.ColumnByName(column.FieldName) != null) { BandedGridColumn colObj = this.bandedGridView.Columns[column.FieldName]; colObj.VisibleIndex = i; colObj.Width = column.Width; colObj.Visible = column.Visible; } } } } /// /// 说明:重写表格选中事件. /// 创建人:王一帆 /// 创建日期:2020-10-30 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The source of the event. /// The instance containing the event data. protected override void OnGridViewCustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e) { if (SystemInfo.Instance.ConditionalStylePriority && e.RowHandle >= 0 && this.GridRowColorsTable != null && this.GridRowColorsTable.Rows.Count > 0) { // 渲染界面数据量过多界面刷新会很慢 DataRow gridRow = this.GridView.GetDataRow(e.RowHandle); foreach (DataRow item in this.GridRowColorsTable.Rows) { string cond = ReplaceHelper.ReplaceRowParam(gridRow, item["condition"] + ""); try { if (!string.IsNullOrWhiteSpace(cond) && ReplaceHelper.EvalCond(cond)) { GridRowColorModel model = new GridRowColorModel(item); if (!string.IsNullOrWhiteSpace(model.BackColor)) { e.Appearance.BackColor = ColorTranslator.FromHtml(model.BackColor); } if (!string.IsNullOrWhiteSpace(model.ForceColor)) { e.Appearance.ForeColor = ColorTranslator.FromHtml(model.ForceColor); } FontStyle fontStyle = FontStyle.Regular; if (model.IsBold) fontStyle |= FontStyle.Bold; if (model.IsItalic) fontStyle |= FontStyle.Italic; if (model.IsStrickOut) fontStyle |= FontStyle.Strikeout; if (model.IsUnderLine) fontStyle |= FontStyle.Underline; e.Appearance.FontStyleDelta = fontStyle; } } catch (Exception) { //LogHelper.Instance.WriteLog("GridView RowCellStyle Error. Condition:" + model.Condition + ";EvalCondtion:" + cond); } } } // 仅当单元格没有被选中时,才设置行选中颜色,否则保持默认的选中色 if (e.RowHandle == bandedGridView.FocusedRowHandle && !bandedGridView.IsCellSelected(e.RowHandle, e.Column)) { e.Appearance.BackColor = ColorTranslator.FromHtml("#9feb6a"); } string PromptText = string.Empty; // 判断单元格值是否为 null 或空 if (PromptMessage.TryGetValue(e.Column.FieldName, out PromptText) && (e.CellValue == null || string.IsNullOrEmpty(e.CellValue.ToString()))) { // 绘制默认单元格背景 e.DefaultDraw(); // 绘制提示文本(灰色、斜体) var appearance = e.Appearance; appearance.ForeColor = Color.Gray; appearance.FontStyleDelta = FontStyle.Italic; e.Graphics.DrawString(PromptText, appearance.Font, new SolidBrush(appearance.ForeColor), e.Bounds, new StringFormat { Alignment = StringAlignment.Near, LineAlignment = StringAlignment.Center }); // 标记事件已处理,避免默认绘制覆盖 e.Handled = true; } } /// /// 说明:重写绘制序号列 /// 创建人:龚宇超 /// 创建日期:2018-04-20 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The source of the event. /// The instance containing the event data. protected override void OnGridViewCustomDrawRowIndicator(object sender, RowIndicatorCustomDrawEventArgs e) { e.Appearance.TextOptions.HAlignment = HorzAlignment.Center; e.Appearance.Options.UseBackColor = true; e.Appearance.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.BackwardDiagonal; if (e.Info.IsRowIndicator) { if (e.RowHandle >= 0) { e.Info.DisplayText = (e.RowHandle + 1).ToString(); } if (bandedGridView.FocusedRowHandle == e.RowHandle) { e.Appearance.BackColor = Color.Blue; e.Info.BackAppearance.BackColor = Color.Blue; e.Appearance.BackColor2 = Color.Blue; e.Info.BackAppearance.BackColor2 = Color.Blue; e.Appearance.ForeColor = Color.Blue; } } } /// /// 说明: /// 创建人:龚宇超 /// 创建日期:2018-04-26 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The grid column. /// The model. protected override void SetColumnSumming(GridColumn gridColumn, GridColumnModel model) { bool isBlankHeader = true;//是空白一级列头 if (moduleModel != null && gridColumn is BandedGridColumn && moduleModel.BandedAddToEnd) { //只有一级表头为空的第一列会显示合计(设置了空白列加在最后才生效) BandedGridColumn bandedGridColumn = gridColumn as BandedGridColumn; if (bandedGridColumn.OwnerBand != null && !string.IsNullOrWhiteSpace(bandedGridColumn.OwnerBand.Caption)) { isBlankHeader = false; } } // 设置底部合计 if (gridColumn.VisibleIndex == 0 && isBlankHeader)//只有空白表头才设置 合计xxx行 { if (this.TotalColumn != null) { this.TotalColumn.Summary.Clear(); } this.TotalColumn = gridColumn; bandedGridView.OptionsView.ShowFooter = true; gridColumn.Summary.AddRange(new GridSummaryItem[] { new GridColumnSummaryItem(DevExpress.Data.SummaryItemType.Count, gridColumn.FieldName, TotalFormat) }); if (SystemInfo.Instance.GroupSpecialMode) { //bandedGridView.GroupSummary.Add(new GridGroupSummaryItem(DevExpress.Data.SummaryItemType.Count, gridColumn.FieldName, gridColumn, "合计: {0:#,###}行")); bandedGridView.OptionsView.GroupFooterShowMode = GroupFooterShowMode.VisibleAlways; } else { bandedGridView.GroupSummary.AddRange(new GridSummaryItem[] { new GridGroupSummaryItem(DevExpress.Data.SummaryItemType.Count, gridColumn.FieldName, null, TotalFormat) }); } } else { if (model.CanSum) { bandedGridView.OptionsView.ShowFooter = true; gridColumn.Summary.AddRange(new GridSummaryItem[] { new GridColumnSummaryItem((!string.IsNullOrEmpty(model.sumCalc) || !string.IsNullOrEmpty(model.SumCond) || model.isSumMerge) ? SummaryItemType.Custom : SummaryItemType.Sum, gridColumn.FieldName, model.SumText + "{0:" + model.DataFormat + "}") }); if (SystemInfo.Instance.GroupSpecialMode) { bandedGridView.GroupSummary.Add(new GridGroupSummaryItem((!string.IsNullOrEmpty(model.sumCalc) || !string.IsNullOrEmpty(model.SumCond) || model.isSumMerge) ? SummaryItemType.Custom : SummaryItemType.Sum, gridColumn.FieldName, gridColumn, model.SumText + "{0:" + model.DataFormat + "}")); bandedGridView.OptionsView.GroupFooterShowMode = GroupFooterShowMode.VisibleAlways; } else { bandedGridView.GroupSummary.AddRange(new GridSummaryItem[] { new GridGroupSummaryItem((!string.IsNullOrEmpty(model.sumCalc) || !string.IsNullOrEmpty(model.SumCond) || model.isSumMerge) ? SummaryItemType.Custom : SummaryItemType.Sum, gridColumn.FieldName, null, model.SumText + "{0:" + model.DataFormat + "}") }); } } } } /// 说明:表格列求和触发事件 /// 创建人:王一帆 /// 创建日期:2021-04-16 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The grid column. /// The model. protected override void OnGridViewSummaryCalculate(object sender, CustomSummaryEventArgs e) { bool isSum = false; var gridView = sender as DevExpress.XtraGrid.Views.BandedGrid.BandedGridView; GridSummaryItem gridSummaryItem = e.Item as GridSummaryItem; GridColumn gridColumn = gridView.Columns[gridSummaryItem.FieldName] as GridColumn; GridColumnModel model = gridColumn.Tag as GridColumnModel; GridViewInfo info = gridView.GetViewInfo() as GridViewInfo; switch (e.SummaryProcess) { //calculation entry point 计算开始时 case DevExpress.Data.CustomSummaryProcess.Start: customSum = 0; SumText = model.sumCalc; sumdr = null; if (!string.IsNullOrEmpty(model.sumCalc)) { DataTable SumTab = new DataTable(); List condition = ReplaceHelper.GetParamFields(model.sumCalc); foreach (string item in condition) { string field = item.Replace("{", "").Replace("}", ""); SumTab.Columns.Add(field); } sumdr = SumTab.NewRow(); } break; //consequent calculations 计算中自定义计算方法 case CustomSummaryProcess.Calculate: DataRow gridRow = gridView.GetDataRow(e.RowHandle); isSum = !string.IsNullOrWhiteSpace(model.SumCond) ? "true".Equals(EvalHelper.Eval(ReplaceHelper.ReplaceEvalCond(ReplaceHelper.ReplaceRowParam(gridRow, model.SumCond))) + "", StringComparison.OrdinalIgnoreCase) : true; if (!string.IsNullOrEmpty(model.sumCalc)) { foreach (DataColumn col in sumdr.Table.Columns) { sumdr[col.ColumnName] = Convert.ToDecimal(string.IsNullOrEmpty(sumdr[col.ColumnName] + "") ? "0" : sumdr[col.ColumnName] + "") + Convert.ToDecimal(string.IsNullOrEmpty(gridRow[col.ColumnName] + "") ? "0" : gridRow[col.ColumnName] + ""); } } else { if (model.isSumMerge && !string.IsNullOrEmpty(e.FieldValue + "")) { if (!string.IsNullOrEmpty(model.MergeGroup)) { string currentGroupName = GetMergeGroupValue(model, gridRow); bool isMergrGroup = !string.IsNullOrEmpty(currentGroupName) && e.RowHandle != 0 ? currentGroupName.Equals(BeforeGroupName) : false; if (model.CanMerge && BeforeClass == Convert.ToDecimal(e.FieldValue) && isMergrGroup) { BeforeClass = Convert.ToDecimal(e.FieldValue); BeforeGroupName = currentGroupName; } else { BeforeClass = Convert.ToDecimal(e.FieldValue); BeforeGroupName = currentGroupName; if (isSum || String.IsNullOrEmpty(model.SumCond)) customSum += Convert.ToDecimal(e.FieldValue); } } else { if (model.CanMerge && BeforeClass == Convert.ToDecimal(e.FieldValue)) { BeforeClass = Convert.ToDecimal(e.FieldValue); } else { BeforeClass = Convert.ToDecimal(e.FieldValue); if (isSum || String.IsNullOrEmpty(model.SumCond)) customSum += Convert.ToDecimal(e.FieldValue); } } } if (isSum) { if (BeforeClass != Convert.ToDecimal(e.FieldValue)) { customSum += Convert.ToDecimal(e.FieldValue); } } } break; //final summary value 计算结束 case CustomSummaryProcess.Finalize: if (gridView.GridControl.DataSourceTable().Rows.Count == 0) break; if (sumdr != null) { foreach (DataColumn col in sumdr.Table.Columns) { string newresult = sumdr[col.ColumnName] + ""; GridColumn newColumn = gridView.Columns[col.ColumnName] as GridColumn; GridColumnModel newModel = newColumn.Tag as GridColumnModel; if (!string.IsNullOrEmpty(newModel.DataFormat)) { //计算后先执行保存小数位数 if (!model.sumCalc.StartsWith("@")) { newresult = string.Format("{0:" + newModel.DataFormat + "}", Convert.ToDecimal(string.IsNullOrEmpty(newresult) ? "0" : newresult)); } } sumdr[col.ColumnName] = newresult + ""; } if (this.ParentControl != null) SumText = ParentControl.ReplaceParentControlValue(model.sumCalc); SumText = ReplaceHelper.ReplaceRowParam(sumdr, SumText); string result = string.Empty; if (SumText.StartsWith("@")) { result = MainImpl.GetResult(SumText.Replace("@", "")) + ""; } else { result = EvalHelper.Eval2(ReplaceHelper.ReplaceEvalCond(SumText)) + ""; } if (result.Equals("NaN") || string.IsNullOrWhiteSpace(result)) result = "0"; if (string.IsNullOrEmpty(model.DataFormat)) { result = Math.Round(Convert.ToDouble(2), model.Decimals, MidpointRounding.AwayFromZero) + ""; } else { //计算后先执行保存小数位数 result = string.Format("{0:" + model.DataFormat + "}", Convert.ToDecimal(result)); } //如果是数值类型,就去掉百分号 //if (model.FieldType == 7 && result.Contains('%')) //{ // result = (double.Parse(result.Replace("%", "")) * 0.01).ToString(); //} e.TotalValue = result; } else { e.TotalValue = customSum; BeforeClass = 0; BeforeGroupName = ""; } break; } } /// /// 说明:多表头设置动态列 /// 创建人:王一帆 /// 创建日期:2021-02-07 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// protected override void SetAutoColumns() { bool isShowFooter = false; if (this.ColumnList == null || this.ColumnList.Count == 0) { this.SuspendLayout(); this.ResumeLayout(); List bandEmptyRows = new List(); List bandFields = new List(); DataRow dr = MainImpl.GetSystemdllTab(this.Model.ModuleCode); bool isEdit = false;//是否可操作 if (dr != null && !(this.Model is DynamicReportModel)) { ModuleModel SysModel = new ModuleModel(dr); isEdit = SysModel.CanEdit; } if (this is BandedGridControlEx) { frozenColumnGridBands.Clear(); frozenGridBands.Clear(); GridBand gridBandEmpty = new GridBand(); List autoFixColumns = new List(); bool hasVisibleBandEmptyRow = false; foreach (GridColumn item in bandedGridView.Columns) { if (item.FieldName.Contains("|")) { int index = item.FieldName.LastIndexOf("|"); string bandField = item.FieldName.Substring(0, index); if (!bandFields.Contains(bandField)) bandFields.Add(bandField); } else { bandEmptyRows.Add(item.FieldName); bool emptyColumnVisible = true; if (item.FieldName.Contains("_")) { string[] colparame = item.FieldName.Split('_'); int width = 0; if (colparame.Length >= 2 && Int32.TryParse(colparame[1], out width)) { emptyColumnVisible = width > 0; } } if (emptyColumnVisible) { hasVisibleBandEmptyRow = true; } } } foreach (string bandName in bandFields) { GridBand gridBand = new GridBand(); gridBand.Caption = bandName; gridBand.AppearanceHeader.Options.UseFont = true; gridBand.AppearanceHeader.Font = new Font("宋体", 9, FontStyle.Bold); gridBand.AppearanceHeader.Options.UseTextOptions = true; gridBand.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center; bandedGridView.Bands.AddRange(new GridBand[] { gridBand }); //bandFields += "|" + item.BandFields; } if (bandEmptyRows != null && bandEmptyRows.Count() > 0) { // 空白列 gridBandEmpty.Caption = ""; gridBandEmpty.AppearanceHeader.Options.UseFont = true; gridBandEmpty.AppearanceHeader.Font = new Font("宋体", 9, FontStyle.Bold); gridBandEmpty.AppearanceHeader.Options.UseTextOptions = true; gridBandEmpty.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center; gridBandEmpty.Visible = hasVisibleBandEmptyRow; bandedGridView.Bands.Insert(0, gridBandEmpty); } bandedGridView.BeginDataUpdate(); // 创建列 for (int i = 0; i < bandedGridView.Columns.Count; i++) { BandedGridColumn col = bandedGridView.Columns[i]; int vsNum = 0; bool isNum = false; string FieldName = col.FieldName; string bandTitle = string.Empty; bool isFixColumn = false;//是否有冻结列 col.VisibleIndex = i; if (col.FieldName.Contains("|")) { string[] colSplit = col.FieldName.Split('|'); if (colSplit.Length >= 2) { FieldName = colSplit[1]; bandTitle = colSplit[0]; } } if (col.VisibleIndex == 0) { col.Summary.AddRange(new GridSummaryItem[] { new GridColumnSummaryItem(DevExpress.Data.SummaryItemType.Count, col.FieldName, TotalFormat) }); if (SystemInfo.Instance.GroupSpecialMode) { //bandedGridView.GroupSummary.Add(new GridGroupSummaryItem(DevExpress.Data.SummaryItemType.Count, col.FieldName, col, "合计: {0:#,###}行")); bandedGridView.OptionsView.GroupFooterShowMode = GroupFooterShowMode.VisibleAlways; } else { GridView.GroupSummary.AddRange(new GridSummaryItem[] { new GridGroupSummaryItem(DevExpress.Data.SummaryItemType.Count, col.FieldName, null, TotalFormat) }); } } if (FieldName.Contains("_")) { string[] colparame = FieldName.Split('_'); if (colparame.Length >= 2) { FieldName = colparame[0]; isNum = Int32.TryParse(colparame[1], out vsNum); if (vsNum == 0) col.Visible = false; if (colparame.Length > 2) { bool visible = "1".Equals(colparame[2]); // 设置底部合计 if (visible) { isShowFooter = true; string dataFormat = colparame.Length > 3 ? colparame[3] : ""; col.Summary.AddRange(new GridSummaryItem[] { new GridColumnSummaryItem(SummaryItemType.Sum, col.FieldName, "{0:" + dataFormat + "}") }); if (SystemInfo.Instance.GroupSpecialMode) { bandedGridView.GroupSummary.Add(new GridGroupSummaryItem(DevExpress.Data.SummaryItemType.Sum, col.FieldName, col, "{0:" + dataFormat + "}")); bandedGridView.OptionsView.GroupFooterShowMode = GroupFooterShowMode.VisibleAlways; } else { GridView.GroupSummary.AddRange(new GridSummaryItem[] { new GridGroupSummaryItem(SummaryItemType.Sum, col.FieldName, null, "{0:" + dataFormat + "}") }); } } if (colparame.Length > 3) { string dataFormat = colparame[3]; if (!string.IsNullOrWhiteSpace(dataFormat)) { col.DisplayFormat.FormatType = FormatType.Custom; col.DisplayFormat.FormatString = dataFormat; } } if (colparame.Length > 4) { //冻结列 isFixColumn = "1".Equals(colparame[4]); } } } } if (!string.IsNullOrEmpty(bandTitle)) { // 绑定了多表头显示 GridBand gridBand = bandedGridView.Bands.Cast().FirstOrDefault(x => x.Caption == bandTitle); if (gridBand != null) { gridBand.Columns.Add(col);// GridBandColumnCollection gcc = gridBand.Columns; } bandedGridView.Columns.Add(col); } else { // 未绑定多表头则直接显示 if (bandEmptyRows != null && bandEmptyRows.Contains(col.FieldName)) { gridBandEmpty.Columns.Add(col); } bandedGridView.Columns.Add(col); } if (isFixColumn && col.OwnerBand != null) { autoFixColumns.Add(col); } if (isNum) col.Width = vsNum; col.OptionsColumn.AllowEdit = isEdit; //col.FieldName = FieldName; //col.Name = FieldName; col.Caption = FieldName; col.OptionsFilter.AutoFilterCondition = AutoFilterCondition.Contains; col.OptionsFilter.FilterPopupMode = FilterPopupMode.CheckedList; col.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center; bandedGridView.OptionsView.ShowFooter = isShowFooter; } foreach (IGrouping group in autoFixColumns.GroupBy(x => x.OwnerBand).ToList()) { GridBand gridBand = group.Key; List fixColumns = group.ToList(); List visibleColumns = gridBand.Columns.Cast().Where(x => x.Visible && x.Width > 0).ToList(); if (visibleColumns.Count > 0 && visibleColumns.All(x => fixColumns.Contains(x))) { if (!frozenGridBands.Contains(gridBand)) frozenGridBands.Add(gridBand); gridBand.Fixed = FixedStyle.Left; } else { foreach (BandedGridColumn fixColumn in fixColumns) { if (fixColumn.OwnerBand != null) { FixLeftItemClick(fixColumn, EventArgs.Empty); } } } } bandedGridView.EndDataUpdate(); //this.bandedGridView.DataSource = bandedGridView.DataSource as DataTable; } } } /// /// 说明:重写OnGridViewCellValueChanged /// 创建人:龚宇超 /// 创建日期:2018-09-18 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The sender. /// The instance containing the event data. //protected void OnGridViewCellValueChanged(object sender, CellValueChangedEventArgs e) //{ // int index = this.GridView.GetFocusedDataSourceRowIndex(); // string columnName = e.Column.FieldName; // if (!modifyThePosition.ContainsKey(index)) // { // modifyThePosition.Add(index, columnName); // } // else // { // if (!modifyThePosition[index].Equals(columnName)) modifyThePosition[index] = modifyThePosition[index] + "," + columnName; // } //} protected void OnGridViewCellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e) { try { GridView gridView = this.gridControl.MainView as GridView; DataTable dataTable = this.gridControl.DataSourceTable(); if (e.Column.Tag == null) return; GridColumnModel model = e.Column.Tag as GridColumnModel; if (model == null) return; //值改变时,如果是验证是否重复的列报错就清除 if (RepeatedVerificationNames.Count > 0) { DataColumn[] datas = this.GridView.GetDataRow(e.RowHandle).GetColumnsInError(); foreach (DataColumn item in datas) { if (this.GridView.GetDataRow(e.RowHandle).GetColumnError(item.ColumnName).Equals("数据重复")) { this.GridView.GetDataRow(e.RowHandle).ClearErrors(); break; } } } int rowHandle = gridView.GetDataSourceRowIndex(e.RowHandle); //根据某一列的值自动填充对应值 if (this.AutoPadDataReleColList.Count > 0) { foreach (GridColumnModel selectColumnModel in AutoPadDataReleColList) { if (!string.IsNullOrEmpty(selectColumnModel.AutoPadDataReleColName)) { string value = dataTable.Rows[rowHandle][selectColumnModel.FieldName] + ""; string[] dataReleColNames = selectColumnModel.AutoPadDataReleColName.TrimEnd(',').Split(','); if (dataReleColNames.Contains(e.Column.FieldName)) { DataRow[] selectRows = dataTable.Select().Where(n => n[selectColumnModel.FieldName].Equals(value)).ToArray(); foreach (DataRow selectRow in selectRows) { int dataSourceIndex = dataTable.Rows.IndexOf(selectRow); int index = this.bandedGridView.GetRowHandle(dataSourceIndex); selectRow[e.Column.FieldName] = e.Value; //关联 if (!string.IsNullOrEmpty(model.UnionFields)) { this.SetUnionValue(model, e.Value + "", index); } //计算规则配置在结果字段上,所以无需验证当前操作控件 this.SetCalcValue(model, e.Value + "", index); } } } } } //关联 if (!string.IsNullOrEmpty(model.UnionFields)) { this.SetUnionValue(model, e.Value + "", e.RowHandle); } //计算规则配置在结果字段上,所以无需验证当前操作控件 this.SetCalcValue(model, e.Value + "", rowHandle); this.SetUpperValue(model, e.RowHandle, e.Value + ""); this.SetDisableColumn(model, e.RowHandle, e.Value + ""); //验证数据长度 if (model.LimitLength > 0 && e.Value != null) { DataRow HandleRow = this.bandedGridView.GetDataRow(e.RowHandle); int MaxInputLength = System.Text.Encoding.Default.GetBytes(e.Value.ToString()).Length; if (model.LimitLength < MaxInputLength) HandleRow.SetColumnError(HandleRow.Table.Columns[e.Column.ColumnHandle], "当前输入文本超过设定长度!");//满足条件设置错误信息 else HandleRow.ClearErrors();//清除错误信息 } int isRepeat = 0; var rows = this.gridControl.DataSourceTable().Select().ToList().Where(n => n[e.Column.FieldName].Equals(Convert.ChangeType(e.Value, e.Column.ColumnType))); if (isRepeat == 1 && !string.IsNullOrEmpty(e.Value.ToString()) && rows.Count() > 0) { MessageUtil.Show("不能输入重复值!"); this.bandedGridView.SetRowCellValue(e.RowHandle, e.Column, string.Empty); this.bandedGridView.FocusedRowHandle = e.RowHandle; this.bandedGridView.FocusedColumn = e.Column; } } catch (Exception ex) { string Message = ErrorMessage.PromptErrorMessage(ex, Model.ModuleCode); MessageUtil.Show(Message, ex.Message); } } /// /// 说明:重写BandedGridViewKeyDown /// 创建人:龚宇超 /// 创建日期:2018-09-18 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The sender. /// The instance containing the event data. protected override void OnGridViewKeyDown(object sender, KeyEventArgs e) { // 替换本列下所有数据为当前单元格数据 if (e.KeyCode == Keys.F6 || e.KeyCode == Keys.F7) { GridColumn column = this.bandedGridView.FocusedColumn; if (column != null && column.OptionsColumn.AllowEdit && this.bandedGridView.RowCount > 0 && this.bandedGridView.OptionsBehavior.Editable) { // 允许操作 int focusedRowHandle = this.bandedGridView.FocusedRowHandle; int totalRowCount = this.bandedGridView.RowCount; GridCell[] cells = this.bandedGridView.GetSelectedCells(); if (cells.Length == 1 && focusedRowHandle + 1 < totalRowCount) { DataTable sourceTab = GridView.GridControl.DataSourceTable(); if (sourceTab.Columns.Contains("PrecomputedMaxDate") && column.Tag == null) { return; } if (MessageUtil.Show(e.KeyCode == Keys.F6 ? ResourceKeys.IsReplaceAllEmptyColumn : ResourceKeys.IsReplaceAllColumn, MessageBoxButtons.YesNo) == DialogResult.Yes) { object obj = this.bandedGridView.GetFocusedRowCellValue(column); if (obj != null) { for (int i = focusedRowHandle; i < totalRowCount; i++) { bandedGridView.FocusedRowHandle = i; object obj2 = bandedGridView.GetRowCellValue(i, column); if (e.KeyCode == Keys.F6) { // F6 覆盖当前列下所有为空的列 if (string.IsNullOrEmpty(obj2 + "")) bandedGridView.SetRowCellValue(i, column, obj); } else { // F7 覆盖当前列下所有列 bandedGridView.SetRowCellValue(i, column, obj); } bandedGridView.PostEditor(); } e.Handled = true; } } } else { e.Handled = true; } } } // 已当前列为基准,按顺序生成本列数据 if (e.KeyCode == Keys.F8) { GridColumn column = this.bandedGridView.FocusedColumn; if (column != null && column.OptionsColumn.AllowEdit && this.bandedGridView.RowCount > 0 && this.bandedGridView.OptionsBehavior.Editable) { // 允许操作 int focusedRowHandle = this.bandedGridView.FocusedRowHandle; int totalRowCount = this.bandedGridView.RowCount; GridCell[] cells = this.bandedGridView.GetSelectedCells(); if (cells.Length == 1 && focusedRowHandle + 1 < totalRowCount) { if (MessageUtil.Show(ResourceKeys.IsGenerateAllColumn, MessageBoxButtons.YesNo) == DialogResult.Yes) { bool isExec = false; long value = 0; object obj = this.bandedGridView.GetFocusedRowCellValue(column); if (!string.IsNullOrEmpty(obj + "")) { isExec = Int64.TryParse(obj + "", out value); } else { isExec = MessageUtil.Show(ResourceKeys.SelectColumnValueTypeNotNumber, MessageBoxButtons.YesNo) == DialogResult.Yes; value = 1; } if (isExec) { // 继续执行 for (int i = focusedRowHandle; i <= totalRowCount; i++) { bandedGridView.FocusedRowHandle = i; bandedGridView.SetRowCellValue(i, column, value++); bandedGridView.PostEditor(); } e.Handled = true; } } } else { e.Handled = true; } } } // 复制单元格 if (e.Control && e.KeyCode == Keys.C) { GridCell[] cells; //复选框状态 if (GridView.OptionsSelection.MultiSelect == true && GridView.OptionsSelection.MultiSelectMode == GridMultiSelectMode.CheckBoxRowSelect && GridView.OptionsSelection.EnableAppearanceFocusedCell == false && this.GridView.GetSelectedRows().Length == 0) { //GridViewInfo info = gridView.GetViewInfo() as GridViewInfo; //GridCellInfo cellInfo = info.GetGridCellInfo(gridView.FocusedRowHandle, gridView.FocusedColumn); GridCell cell = new GridCell(GridView.FocusedRowHandle, GridView.FocusedColumn); cells = new GridCell[] { cell }; } else cells = this.GridView.GetSelectedCells(); if (cells.Length == 1 || GridView.OptionsView.AllowCellMerge) { object obj = GridView.GetFocusedRowCellValue(GridView.FocusedColumn); if (obj != null) { Clipboard.SetDataObject(obj + ""); e.Handled = true; } } else { GridView.CopyToClipboard(); e.Handled = true; } } if (e.Modifiers.CompareTo(Keys.Control) == 0 && e.KeyCode == Keys.V) { // 清除排序 this.GridView.Columns.ClearAllSort(); //if (this.gridView.IsFindPanelVisible) //{ // MessageUtil.Show("搜索模式下无法粘贴行."); // return; //} object _objData = null; IDataObject dataObj = Clipboard.GetDataObject(); if (dataObj.GetDataPresent(DataFormats.Text)) _objData = dataObj.GetData(DataFormats.Text); if (_objData != null) { string _tempStr = _objData.ToString(); _tempStr = Regex.Replace(_tempStr, "\"[^\"]*(?:\"\"[^\"]*)*\"", m => m.Value.Replace("\r\n", "{lskj}").Replace("\"", "")); int _rowNumber = 1; int _pasteRowCount = 1; string[] _split = { "\r\n" }; string[] _arrayRowStr = _tempStr.Split(_split, StringSplitOptions.None); if (_arrayRowStr.Length < 1) return; GridColumn focColumn = this.GridView.FocusedColumn; focColumn = focColumn == null ? this.GridView.Columns[0] : focColumn; if (focColumn != null) { DataTable table = GridView.GridControl.DataSourceTable(); int beforeNumber = table.Rows.Count; _rowNumber = this.GridView.FocusedRowHandle; if (_rowNumber < 0) { _rowNumber = 0; } if (_arrayRowStr.Length != GridView.SelectedRowsCount) { //选择区域与粘贴行数不匹配 } _pasteRowCount = _arrayRowStr.Length; for (int i = 0; i < _pasteRowCount; i++) { string[] _arrayStr2 = _arrayRowStr[i].Split('\t'); if ((i == _pasteRowCount - 1 && _arrayRowStr[_pasteRowCount - 1].Replace("\r\n", "").Trim() == "")) continue; DataRow newRow = null; if (_rowNumber + 1 > table.Rows.Count) { newRow = table.NewRow(); //table.Rows.Add(newRow); GridColumnCollection gridColumns = this.GridView.Columns; this.GridView.FocusedRowHandle = _rowNumber; foreach (GridColumn col in gridColumns) { GridColumnModel model = col.Tag as GridColumnModel; string fieldValue = BaseImpl.GetDefaultValue(model.DefaultValue); if (model.DefaultValue.Contains("{#") && this.ParentControl != null) { fieldValue = this.ParentControl.ReplaceParentControlValue(model.DefaultValue); if (!string.IsNullOrEmpty(fieldValue)) { newRow[col.FieldName] = fieldValue; } } else if (!string.IsNullOrEmpty(model.DefaultValue) && !model.DefaultValue.Contains("{ROW_")) { newRow[col.FieldName] = fieldValue; } } } this.GridView.FocusedRowHandle = _rowNumber; if (_arrayStr2.Length == 0) _arrayStr2[0] = _arrayRowStr[i]; int _colNumber = beforeNumber == 0 && this.GridView.OptionsView.NewItemRowPosition != NewItemRowPosition.Bottom ? 0 : focColumn.VisibleIndex; for (int j = 0; j < _arrayStr2.Length; j++) { GridColumn col = GridView.VisibleColumns[_colNumber]; GridColumnModel model = col.Tag as GridColumnModel; if (DateTime.TryParse(col.FieldName, out _) || (model.CanCopy || ((GridView.OptionsBehavior.Editable) && (GridView.VisibleColumns[_colNumber].OptionsColumn.AllowEdit)))) { // 返回ID类型特殊处理 string cellValue = _arrayStr2[j]; if (!string.IsNullOrEmpty(cellValue)) cellValue = cellValue.Replace("{lskj}", "\n"); bool IsTextEqualValue = false; object value = model != null && ControlType.IsValue(model.FieldType) ? GetValueByCaption(model, col.ColumnEdit, cellValue, out IsTextEqualValue) : cellValue; DateTime dateValue = new DateTime(); // 避免下拉框值替换失败提示错误 if (model != null && !IsTextEqualValue && ((ControlType.IsValue(model.FieldType) && cellValue == value + "") || (ControlType.LabTextInt == model.FieldType && (value + "").IsChinese()) || (ControlType.IsDate(model.FieldType) && !DateTime.TryParse(value + "", out dateValue)))) { _colNumber += 1; continue; } if (newRow == null) { GridView.SetRowCellValue(_rowNumber, col, value); } else { newRow[col.FieldName] = value; } //gridView.SetRowCellValue(_rowNumber, col, value); } _colNumber += 1; } _rowNumber += 1; if (newRow != null) { // 其它处理(如绑定左侧树结构数据) if (OnParseGridDataCallBack != null) this.OnParseGridDataCallBack(newRow); table.Rows.Add(newRow); } else { GridView.UpdateCurrentRow(); } } this.GridView.ShowEditor(); e.Handled = true; //SendKeys.Send("{Esc}"); } } } } /// /// 右键加载 /// /// /// protected void OnGridViewPopupMenuShowing(object sender, PopupMenuShowingEventArgs e) { try { ////没有设置右键时,ContextMenuStrip为空。右键菜单可能会必须选中才能关闭,设置空ContextMenuStrip可用解决 if (this.gridControl.ContextMenuStrip == null) { ContextMenuStrip MenuStrip = new ContextMenuStrip(); this.gridControl.ContextMenuStrip = MenuStrip; } if (e.MenuType == GridMenuType.Column) { GridViewColumnMenu columnMenu = e.Menu as GridViewColumnMenu; GridViewColumnMenu BANDMenu = e.Menu as GridViewBandMenu; DXMenuItem itemSaveColumn = new DXMenuItem("保存表格属性", SaveItemClick); DXMenuItem itemResetColumn = new DXMenuItem("重置表格属性", ResetItemClick); DXMenuItem itemFixLeft = new DXMenuItem("冻结列", FixLeftItemClick); DXMenuItem itemFixLeftAll = new DXMenuItem("冻结列(所有列)", FixLeftAllItemClick); DXMenuItem itemUnFix = new DXMenuItem("清除冻结", UnFixItemClick); DXMenuItem itemUnFixAll = new DXMenuItem("清除冻结(所有列)", itemUnFixAllClick); DXMenuItem itemSetExportColumn = new DXMenuItem("设置导出列", SetExportItemClick); DXMenuItem itemExportColumn = new DXMenuItem("导出表格数据", ExportItemClick); DXMenuItem itemPrintColumn = new DXMenuItem("打印表格数据", PrintItemClick); DXMenuItem itemSortColumn = new DXMenuItem("清除全部列排序", ClearSortItemClick); DXMenuItem itemMultifunction = new DXMenuItem("多功能设置分组", Multifunction); DXMenuItem itemColumnSift = new DXMenuItem("一键设置列筛选条件", InstColumnSift); DXMenuItem itemChartColumn = new DXMenuItem("一键图表展示", ChartShowClick); DXMenuItem itemBsChartColumn = new DXMenuItem("一键Bs图表展示", BsChartShowClick); DXMenuItem itemBsChartShowClick = new DXMenuItem("一键所有列属性设置", InstAllColumn); if (columnMenu.Column == null) { GridBand gridBand = (e.HitInfo as DevExpress.XtraGrid.Views.BandedGrid.ViewInfo.BandedGridHitInfo).Band; itemFixLeft.Tag = itemFixLeftAll.Tag = itemUnFix.Tag = gridBand; //如果先冻结了二级表头,在准备冻结对应的一级表头,则无法冻结 if (frozenColumnGridBands.ContainsValue(gridBand)) { columnMenu.Items.AddRange(new DXMenuItem[] { itemUnFix, itemUnFixAll }); } else { columnMenu.Items.AddRange(new DXMenuItem[] { itemFixLeft, itemUnFix, itemUnFixAll }); } } else { itemColumnSift.Tag = itemFixLeft.Tag = itemFixLeftAll.Tag = itemUnFix.Tag = e.HitInfo.Column as BandedGridColumn; GridBand gridBand = (e.HitInfo.Column as BandedGridColumn).OwnerBand; if (frozenGridBands.Contains(gridBand)) { columnMenu.Items.AddRange(new DXMenuItem[] { itemSaveColumn, itemResetColumn, itemFixLeft, itemUnFixAll, itemColumnSift }); } else { columnMenu.Items.AddRange(new DXMenuItem[] { itemSaveColumn, itemResetColumn, itemFixLeft, itemUnFix, itemUnFixAll, itemColumnSift }); } } columnMenu.Items.Add(itemSetExportColumn); if (ExportPermission) columnMenu.Items.Add(itemExportColumn); columnMenu.Items.AddRange(new DXMenuItem[] { itemPrintColumn, itemSortColumn, itemMultifunction, itemBsChartShowClick }); } else if (e.MenuType == GridMenuType.Summary) { GridHitInfo info; Point pt = this.bandedGridView.GridControl.PointToClient(System.Windows.Forms.Control.MousePosition); info = this.bandedGridView.CalcHitInfo(pt); DXMenuCheckItem menuItemCell = new DXMenuCheckItem(); menuItemCell.Tag = info; menuItemCell.Caption = "复制合计"; menuItemCell.Click += new EventHandler(OnMenuItem_Click); DXMenuCheckItem menuItemRow = new DXMenuCheckItem(); menuItemRow.Caption = "复制合计行"; menuItemRow.Tag = info; menuItemRow.Click += new EventHandler(OnMenuItem_Click); e.Menu.Items.AddRange(new DXMenuCheckItem[] { menuItemCell, menuItemRow }); } } catch (Exception ex) { string Message = ErrorMessage.PromptErrorMessage(ex, Model.ModuleCode); MessageUtil.Show(Message, ex.Message); } } /// ///冻结列列名和对应的一级标题 /// public Dictionary frozenColumnGridBands = new Dictionary(); /// ///直接冻结的一级标题 /// public List frozenGridBands = new List(); /// /// 说明:保存多表格属性 /// 创建人:王一帆 /// 创建日期:2022-05-19 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The sender. /// The instance containing the event data. protected virtual void SaveItemClick(object sender, EventArgs e) { if (string.IsNullOrEmpty(this.CustomColumKey)) { MessageUtil.Show(ResourceKeys.NotSettingResetColumn); return; } if (this.ColumnList == null || this.ColumnList.Count == 0) { MessageUtil.Show("动态列无法保存属性"); return; } DataRow rowItem = null; bool success = BaseImpl.HasExistsDataRow(ResourceKeys.SettingTableName, "formKey", CustomColumKey.ToString(), string.Format(" and OperatorId='{0}' ", ERPInfo.Instance.UserId), out rowItem); if (!success) { MessageUtil.Show(ResourceKeys.NotFoundSettingColumnTable); return; } if (MessageUtil.Show(ResourceKeys.IsSaveColumn, MessageBoxButtons.YesNo) == DialogResult.Yes) { try { if (rowItem == null) { success = this.bandedGridView.SaveCustomColumnToDatabase(this.CustomColumKey); } else { success = this.bandedGridView.UpdateCustomColumnToDatabase(this.CustomColumKey); } #region old if (ERPInfo.Instance.UserName == "管理员") { string[] keys = CustomColumKey.Split('_'); if (keys.Count() > 1) { string ModuleTypes = keys[0]; string ModuleKey = keys[1]; int ModelType = ControlType.ModelType(ModuleTypes); string tmpsql = string.Empty; string colTable = string.Empty; string keyField = string.Empty; string stepCode = string.Empty; int keyOrder = 0; //DXMenuItem item = sender as DXMenuItem; //GridView grv = item.Tag as GridView; //基础档案主表 if (ModelType == 1 || ModelType == 2) { colTable = "p_systemwordbooktab"; tmpsql = "select top 1 orderid from p_systemwordbooktab where formKey='" + ModuleKey + "' order by orderid"; object obj = SqlHelper.ExecuteScalar(CommandType.Text, tmpsql); if (obj != null) { keyField = "formKey"; keyOrder = Convert.ToInt32(obj); } } if (ModelType == 2 && string.IsNullOrEmpty(keyField)) { colTable = "p_systemDlltabDetailGrid"; tmpsql = "select top 1 orderid from p_systemDlltabDetailGrid where detailKey='" + ModuleKey + "' order by orderid"; object obj = SqlHelper.ExecuteScalar(CommandType.Text, tmpsql); if (obj != null) { keyField = "detailKey"; keyOrder = Convert.ToInt32(obj); } } ////单据明细 if (ModelType == 3) { colTable = "p_systembillDetail"; keyField = "typecode"; ModuleKey = Model.ModuleCode; } ////单据来源主信息 if (ModelType == 4) { colTable = "p_systembillsourcegrid"; keyField = "sourcekey"; } ////单据来源明细信息 if (ModelType == 5) { colTable = "p_systembillsourcedetail"; keyField = "sourcekey"; } //单据审核列表 if (ModelType == 6) { colTable = "p_systembillstepgrid"; keyField = "typeCode"; if (!string.IsNullOrEmpty(ModuleKey) && keys.Length == 5) { ModuleKey = keys[2]; stepCode = keys[3]; } } //基础档案审核列表 if (ModelType == 7) { colTable = "p_systemdlltabflowstepgrid"; keyField = "typeCode"; if (!string.IsNullOrEmpty(ModuleKey) && keys.Length == 5) { ModuleKey = keys[2]; stepCode = keys[3]; } } // 单据审核附加信息 if (ModelType == 8) { colTable = "p_systembillauditAttachDetail"; keyField = "attachKey"; } tmpsql = ""; if (ModelType != 0 && !string.IsNullOrEmpty(keyField)) { foreach (GridColumn col in GridView.Columns) { //+ ((ModelType == 1) && (col.VisibleIndex == -1) ? " ,vislble=1" : "") tmpsql = tmpsql + "update " + colTable + " set width=" + col.Width.ToString() + (col.VisibleIndex != -1 ? ",orderid=" + (col.VisibleIndex + keyOrder + (ModelType == 1 ? 1 : 0)).ToString() : "") + " where " + keyField + "='" + ModuleKey + "' and fieldname='" + col.FieldName + "'"; if (ModelType == 1 || ModelType == 2) tmpsql = tmpsql + " and orderid<>" + keyOrder.ToString(); if (ModelType == 7 || ModelType == 6) tmpsql = tmpsql + " and stepCode=" + stepCode; tmpsql = tmpsql + ";"; } //MessageBox.Show(tmpsql); SqlHelper.ExecuteNonQuery(tmpsql); } } } #endregion MessageUtil.Show(success ? ResourceKeys.SaveSuccess : ResourceKeys.SaveFault); } catch (SqlException sex) { if (sex.Message.Contains(ResourceKeys.FieldLenIsShort) && MessageUtil.Show(ResourceKeys.SaveFault + "\r\n" + ResourceKeys.CanUpgradeTable, MessageBoxButtons.YesNo) == DialogResult.Yes && BaseImpl.UpdateTableField(ResourceKeys.SettingTableName, "formKey", "varchar(200)")) { MessageUtil.Show(ResourceKeys.UpdateSuccess); } } catch (Exception ex) { LogHelper.Instance.WriteError(ex); string Message = ErrorMessage.PromptErrorMessage(ex, Model.ModuleCode); MessageUtil.Show(Message, ex.Message); } } } /// /// 说明:验证表格列是否有为空的值 /// 创建人:龚宇超 /// 创建日期:2017-12-08 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// true if XXXX, false otherwise. public override bool VerifyNull() { DataTable table = this.GridControl.DataSourceTable().TrimEmptyRows(); List columns = this.ColumnList.FindAll(x => x.CanNull); foreach (DataRow item in table.Rows) { foreach (GridColumnModel model in columns) { BandedGridColumn column = this.bandedGridView.Columns[model.FieldName]; string value = item[model.FieldName] + ""; string displayText = this.bandedGridView.GetDisplayTextByColumnValue(column, item[model.FieldName]); if (string.IsNullOrWhiteSpace(value) || string.IsNullOrWhiteSpace(displayText)) { MessageUtil.Show(string.Format(ResourceKeys.NullField, model.FieldText)); this.bandedGridView.Focus(); this.bandedGridView.SelectRowHandler(table.Rows.IndexOf(item)); this.bandedGridView.FocusedColumn = this.bandedGridView.Columns[model.FieldName]; this.bandedGridView.SelectCell(bandedGridView.FocusedRowHandle, this.bandedGridView.Columns[model.FieldName]); this.bandedGridView.ShowEditorByMouse(); return false; } } } return true; } /// /// 冻结 /// /// /// protected virtual void FixLeftItemClick(object sender, EventArgs e) { try { DXMenuItem item = sender as DXMenuItem; BandedGridColumn bgc = sender is BandedGridColumn ? sender as BandedGridColumn : item.Tag as BandedGridColumn; if (bgc != null) { if (frozenColumnGridBands.ContainsKey(bgc.FieldName)) return; if (bgc.OwnerBand.Columns.Count == 1) { //当前一级目录的子目录全部是冻结状态,就把一级目录冻结了,并合并之前的子目录 GridBand gridBand = bgc.OwnerBand; if (!frozenGridBands.Contains(gridBand)) frozenGridBands.Add(gridBand); gridBand.Fixed = FixedStyle.Left; //合并一级标题 List foundKeys = new List();//对应子目录 foreach (KeyValuePair pair in frozenColumnGridBands) { if (pair.Value == gridBand) { BandedGridColumn gridColumn = this.bandedGridView.Columns[pair.Key + ""]; if (gridColumn != null) { foundKeys.Add(pair.Key); bandedGridView.Bands.Remove(gridColumn.OwnerBand);//删除当前一级目录 gridColumn.OwnerBand = gridBand;//设置当前的一级目录 } } } foreach (string name in foundKeys) { frozenColumnGridBands.Remove(name); } return; } frozenColumnGridBands.Add(bgc.FieldName, bgc.OwnerBand); GridBand gb = new GridBand(); bandedGridView.Bands.Add(gb); bgc.OwnerBand = gb; gb.Fixed = FixedStyle.Left; } else { GridBand gridBand = item.Tag as GridBand; if (!frozenGridBands.Contains(gridBand)) frozenGridBands.Add(gridBand); gridBand.Fixed = FixedStyle.Left; } } catch (Exception ex) { } } /// /// 清除冻结 /// /// /// protected virtual void UnFixItemClick(object sender, EventArgs e) { try { DXMenuItem item = sender as DXMenuItem; BandedGridColumn bgc = item.Tag as BandedGridColumn; if (bgc != null) { if (!frozenColumnGridBands.ContainsKey(bgc.FieldName)) return; bandedGridView.Bands.Remove(bgc.OwnerBand);//删除当前一级目录 bgc.OwnerBand = frozenColumnGridBands[bgc.FieldName];//设置原本记录的一级目录 frozenColumnGridBands.Remove(bgc.FieldName); string[] columnsName = saveGridBandColumn[bgc.OwnerBand].Split('^'); int index = Array.IndexOf(columnsName, bgc.FieldName); int i = 0; foreach (string name in columnsName) { if (string.IsNullOrWhiteSpace(name)) continue; BandedGridColumn gridColumn = bgc.OwnerBand.Columns[name]; if (gridColumn != null) { gridColumn.ColVIndex = i; i++; } } } else { GridBand gridBand = item.Tag as GridBand; frozenGridBands.Remove(gridBand); gridBand.Fixed = FixedStyle.None; int index = saveGridBands.FindIndex(x => x.Caption.Equals(gridBand.Caption)); this.bandedGridView.Bands.MoveTo(index + 1, gridBand); } } catch (Exception ex) { } } /// /// 清除冻结(全部列) /// /// /// protected virtual void itemUnFixAllClick(object sender, EventArgs e) { foreach (string columnName in frozenColumnGridBands.Keys) { BandedGridColumn bgc = bandedGridView.Columns[columnName]; GridBand band = bgc.OwnerBand; bandedGridView.Bands.Remove(band); bgc.OwnerBand = frozenColumnGridBands[bgc.FieldName]; string[] columnsName = saveGridBandColumn[bgc.OwnerBand].Split('^'); int index = Array.IndexOf(columnsName, bgc.FieldName); int i = 0; foreach (string name in columnsName) { if (string.IsNullOrWhiteSpace(name)) continue; BandedGridColumn gridColumn = bgc.OwnerBand.Columns[name]; if (gridColumn != null) { gridColumn.ColVIndex = i; i++; } } } frozenColumnGridBands = new Dictionary(); foreach (GridBand gridBand in frozenGridBands) { gridBand.Fixed = FixedStyle.None; int index = saveGridBands.FindIndex(x => x.Caption.Equals(gridBand.Caption)); this.bandedGridView.Bands.MoveTo(index + 1, gridBand); } frozenGridBands = new List(); } /// /// 说明:重置表格属性 /// 创建人:龚宇超 /// 创建日期:2018-02-01 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The sender. /// The instance containing the event data. protected virtual void ResetItemClick(object sender, EventArgs e) { try { if (string.IsNullOrEmpty(this.CustomColumKey)) { MessageUtil.Show(ResourceKeys.NotSettingResetColumn); return; } if (!BaseImpl.HasExistsTable(ResourceKeys.SettingTableName)) { MessageUtil.Show(ResourceKeys.NotFoundSettingColumnTable); return; } if (MessageUtil.Show(ResourceKeys.IsResetColumn, MessageBoxButtons.YesNo) == DialogResult.Yes) { bool success = this.bandedGridView.ResetCustomColumnToDatabase(this.CustomColumKey); this.SetCustomColumns(false); if (success) { itemUnFixAllClick(null, null); foreach (GridBand band in this.bandedGridView.Bands) { if (saveGridBandColumn.ContainsKey(band)) { string[] columnsName = saveGridBandColumn[band].Split('^'); int i = 0; foreach (string name in columnsName) { if (string.IsNullOrWhiteSpace(name)) continue; BandedGridColumn gridColumn = bandedGridView.Columns[name]; if (gridColumn != null) { gridColumn.ColVIndex = i; i++; } } } } //foreach (BandedGridColumn column in this.bandedGridView.Columns) //{ // string[] columnsName = saveGridBandColumn[column.OwnerBand].Split('^'); // int index = Array.IndexOf(columnsName, column.FieldName); // column.VisibleIndex = index; //} } MessageUtil.Show(success ? ResourceKeys.ResetSuccess : ResourceKeys.ResetFault); } } catch (Exception ex) { string Message = ErrorMessage.PromptErrorMessage(ex, Model.ModuleCode); MessageUtil.Show(Message, ex.Message); } } /// /// 说明:清除全部列排序 /// 创建人:龚宇超 /// 创建日期:2018-02-01 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The sender. /// The instance containing the event data. protected virtual void ClearSortItemClick(object sender, EventArgs e) { try { this.bandedGridView.Columns.ClearAllSort(); } catch (Exception ex) { string Message = ErrorMessage.PromptErrorMessage(ex, Model.ModuleCode); MessageUtil.Show(Message, ex.Message); } } /// /// 说明:多功能设置列条件筛选 /// 创建人:王一帆 /// 创建日期:2021-08-02 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The sender. /// The instance containing the event data. protected virtual void Multifunction(object sender, EventArgs e) { try { //DataTable newDt = this.SetDealWithValueTab(); FrmGridSift frmGridSift = new FrmGridSift(); frmGridSift.CustomColumKey = this.CustomColumKey; //frmGridSift.source = newDt; frmGridSift.ParentGridEx = this; DllModule module = new DllModule { DllName = "", Id = this.Model.ModuleCode, Name = this.Model.FormText, BeforePage = ERPInfo.Instance.PageControl.SelectedTabPage }; module.ModuleForm = frmGridSift; string guid = Guid.NewGuid().ToString(); DevExpress.XtraTab.XtraTabPage tp = new DevExpress.XtraTab.XtraTabPage(); tp.Tag = guid; // 这个必须有不然会提示:"不能向tabControl中添加顶级控件" frmGridSift.TopLevel = false; frmGridSift.Location = new Point(0, 0); frmGridSift.Dock = DockStyle.Fill; frmGridSift.FormBorderStyle = FormBorderStyle.None; tp.Text = this.Model.FormText + "分组统计"; tp.AutoScroll = true; tp.AutoScroll = true; tp.Controls.Add(frmGridSift); tp.ShowCloseButton = DefaultBoolean.True; tp.Dock = DockStyle.Fill; ERPInfo.Instance.PageControl.TabPages.Add(tp); ERPInfo.Instance.PageControl.SelectedTabPage = tp; ERPInfo.Instance.ModuleForms.Add(guid, module); frmGridSift.Show(); } catch (Exception ex) { string Message = ErrorMessage.PromptErrorMessage(ex, Model.ModuleCode); MessageUtil.Show(Message, ex.Message); } } /// /// 说明:设置条件筛选列弹出设置 /// 创建人:王一帆 /// 创建日期:2021-08-02 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The sender. /// The instance containing the event data. protected virtual void InstColumnSift(object sender, EventArgs e) { try { DXMenuItem item = sender as DXMenuItem; BandedGridColumn gridColumn = item.Tag as BandedGridColumn; // 保存流转步骤 FilterState filterState = new FilterState(); filterState.LabelObj.Text = string.Format("设置列{0}筛选条件:", gridColumn.Caption); if (filterState.ShowDialog() == DialogResult.OK) { HeaderColumnSift = gridColumn; SiftEnumObj = filterState.SiftEnumObj; } } catch (Exception ex) { string Message = ErrorMessage.PromptErrorMessage(ex, Model.ModuleCode); MessageUtil.Show(Message, ex.Message); } } public void OnShowFilterPopupCheckedListBox(object sender, DevExpress.XtraGrid.Views.Grid.FilterPopupCheckedListBoxEventArgs e) { try { BandedGridView gridView = (BandedGridView)sender; string actStr = this.bandedGridView.ActiveFilterString;//获取筛选条件 string[] actStr_list = actStr.Split(new string[] { "And" }, StringSplitOptions.None); DataTable datatable = new DataTable(); if ((!actStr_list[0].Contains(e.Column.FieldName) || (this.bandedGridView.OptionsView.ShowAutoFilterRow && e.Column.FilterInfo.Type == ColumnFilterType.AutoFilter)) && actStr != "") { CriteriaOperator criteria_op = this.bandedGridView.ActiveFilterCriteria; GroupOperator group_op = new GroupOperator(); InOperator in_op = new InOperator(); if (this.bandedGridView.ActiveFilterString != "") { if (!actStr_list[0].Contains(e.Column.FieldName) && this.bandedGridView.ActiveFilterCriteria.GetType() == typeof(InOperator)) { in_op = this.bandedGridView.ActiveFilterCriteria as InOperator;//获取筛选规则信息 criteria_op = in_op as CriteriaOperator; for (int i = 0; i < in_op.Operands.Count; i++) { if (in_op.Operands[i].ToString().Contains(e.Column.FieldName)) { in_op.Operands.RemoveRange(i, in_op.Operands.Count - i); break; } else continue; } } else if (!actStr_list[0].Contains(e.Column.FieldName) && this.bandedGridView.ActiveFilterCriteria.GetType() == typeof(GroupOperator)) { group_op = this.bandedGridView.ActiveFilterCriteria as GroupOperator;//获取筛选规则信息 criteria_op = group_op as CriteriaOperator; for (int i = 0; i < group_op.Operands.Count; i++) { if (group_op.Operands[i].ToString().Contains(e.Column.FieldName)) { group_op.Operands.RemoveRange(i, group_op.Operands.Count - i); break; } else continue; } } DataView filteredDataView = this.bandedGridView.DataSource as DataView; string RowFilter = string.Empty; try { datatable = filteredDataView.Table.Select(DevExpress.Data.Filtering.CriteriaToWhereClauseHelper.GetDataSetWhere(criteria_op)).CopyToDataTable(); } catch (Exception) { if (RowFilter.Split(new string[] { "And" }, StringSplitOptions.None)[0].Contains(" is null or ")) { if (RowFilter.Contains("And")) RowFilter = RowFilter.Substring(0, RowFilter.IndexOf(" or ")) + ")" + RowFilter.Substring(RowFilter.IndexOf(" And "), RowFilter.Length - RowFilter.IndexOf(" And ")); else if (actStr_list.Length == 1) RowFilter = RowFilter.Substring(0, RowFilter.IndexOf(" or ")) + ")"; else if (actStr_list.Length > 1) RowFilter = RowFilter.Substring(0, RowFilter.IndexOf(" or ")) + "))"; } datatable = filteredDataView.Table.Select(RowFilter).CopyToDataTable(); } //List list = datatable.AsEnumerable().Select(r => r[e.Column.FieldName]).ToList();//获取筛选后的值 List list = new List(); foreach (DataRow row in datatable.Rows) { if (row[e.Column.FieldName].GetType() == typeof(DateTime)) list.Add(((DateTime)row[e.Column.FieldName]).ToShortDateString()); else list.Add(row[e.Column.FieldName]); } DevExpress.XtraEditors.Controls.CheckedListBoxItemCollection _Items = new DevExpress.XtraEditors.Controls.CheckedListBoxItemCollection(); for (int i = 0; i < e.CheckedComboBox.Items.Count; i++) { var Item_value = e.CheckedComboBox.Items[i].Value as FilterItem; if (Item_value.Value != null) { if (Item_value.Value.GetType() == typeof(DateTime) && list.Contains(((DateTime)Item_value.Value).ToShortDateString())) _Items.Add(e.CheckedComboBox.Items[i]); else if (list.Contains(Item_value.Value)) _Items.Add(e.CheckedComboBox.Items[i]); } else if (Item_value.Value == null) { if (list.Contains(null) || list.Contains("") || list.Contains(DBNull.Value)) _Items.Add(e.CheckedComboBox.Items[i]); } //if (Item_value.Value != null && Item_value.Value.GetType() == typeof(DateTime)) //{ // if (list.Contains(((DateTime)Item_value.Value).ToShortDateString())) // { // _Items.Add(e.CheckedComboBox.Items[i]); // } //} //else if (list.Contains(Item_value.Value) && Item_value.Value != null) //{ // _Items.Add(e.CheckedComboBox.Items[i]); //} //else if (list.Contains(null) && Item_value.Value == null || list.Contains("") && Item_value.Value == null) //{ // _Items.Add(e.CheckedComboBox.Items[i]); //} } e.CheckedComboBox.Items.Clear(); for (int i = 0; i < _Items.Count; i++) { e.CheckedComboBox.Items.Add(_Items[i]); } e.CheckedComboBox.HighlightedItemStyle = HighlightStyle.Skinned; } } if (!SystemInfo.Instance.DisableFilteringQuantity) { DataTable filterTable = gridView.GetGridViewFilteredAndSortedDataToDataTable(); DataRow[] dataRowArray = filterTable.Select(); DevExpress.XtraEditors.Controls.CheckedListBoxItemCollection _Items = new DevExpress.XtraEditors.Controls.CheckedListBoxItemCollection(); for (int i = 0; i < e.CheckedComboBox.Items.Count(); i++) { try { CheckedListBoxItem checkedListBoxItem = e.CheckedComboBox.Items[i]; if (checkedListBoxItem.Value is FilterItem) { FilterItem filterItem = (FilterItem)checkedListBoxItem.Value; string text = filterItem.Text; object value = filterItem.Value; int count = dataRowArray.Where(n => (n[e.Column.FieldName] + "").Equals(value + "")).Count(); checkedListBoxItem.Description = $"{text} ({count})"; if (count > 0) _Items.Add(checkedListBoxItem); } } finally { } } //多表头在使用自带的搜索功能时(ctrl+f),筛选框无法过滤搜索后的内容,根据判断是否有搜索值去手动过滤 bool isSearch = !string.IsNullOrWhiteSpace(gridView.FindFilterText); if (isSearch) { e.CheckedComboBox.Items.Clear(); for (int i = 0; i < _Items.Count; i++) { e.CheckedComboBox.Items.Add(_Items[i]); } e.CheckedComboBox.HighlightedItemStyle = HighlightStyle.Skinned; } } } catch (Exception ex) { string Message = ErrorMessage.PromptErrorMessage(ex, Model.ModuleCode); MessageUtil.Show(Message, ex.Message); } } /// /// 合计行数据复制 /// /// /// private void OnMenuItem_Click(object sender, EventArgs e) { try { DXMenuCheckItem menuItemCell = (DXMenuCheckItem)sender; if (menuItemCell.Caption.Equals("复制合计行")) { string copyFooterRowStr = string.Empty; foreach (GridColumn col in this.bandedGridView.VisibleColumns) { if (!string.IsNullOrWhiteSpace(copyFooterRowStr) && !string.IsNullOrWhiteSpace(col.SummaryText)) { copyFooterRowStr += string.Format("\t{0}", col.SummaryText); } else if (string.IsNullOrWhiteSpace(copyFooterRowStr) && !string.IsNullOrWhiteSpace(col.SummaryText)) { copyFooterRowStr += col.SummaryText; } } if (!string.IsNullOrWhiteSpace(copyFooterRowStr)) Clipboard.SetText(copyFooterRowStr); } else { GridHitInfo info = menuItemCell.Tag as GridHitInfo; if (info != null) { DevExpress.XtraGrid.Drawing.GridFooterCellInfoArgs footerCell = info.GetType().GetProperty("FooterCell").GetValue(info, null) as DevExpress.XtraGrid.Drawing.GridFooterCellInfoArgs; if (footerCell != null) { string value = footerCell.DisplayText; if (!string.IsNullOrWhiteSpace(value)) Clipboard.SetText(value); } } } } catch (Exception ex) { MessageUtil.Show(ex.Message); } } /// /// 点击Footer单元格复制信息 /// 创建人:tdx /// 创建日期:2022/9/26 /// /// /// private void OnBandedGridView_Click(object sender, EventArgs e) { GridHitInfo info; Point pt = this.bandedGridView.GridControl.PointToClient(System.Windows.Forms.Control.MousePosition); info = this.bandedGridView.CalcHitInfo(pt); if (info != null) { DevExpress.XtraGrid.Drawing.GridFooterCellInfoArgs footerCell = info.GetType().GetProperty("FooterCell").GetValue(info, null) as DevExpress.XtraGrid.Drawing.GridFooterCellInfoArgs; if (footerCell != null) { string value = footerCell.DisplayText; if (!string.IsNullOrWhiteSpace(value)) Clipboard.SetText(value); } } } /// /// 说明:表格双击打开模块配置 /// 创建人:龚宇超 /// 创建日期:2018-08-13 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// private void OnBandedGridViewDoubleClick(object sender, EventArgs e) { try { DataRow mSelectRow = this.bandedGridView.GetFocusedDataRow(); if (this.gridControl.ContextMenuStrip != null) { Dictionary DbClickItemDic = new Dictionary(); foreach (ToolStripItem cms in this.gridControl.ContextMenuStrip.Items) { GridRightMenuModel model = cms.Tag as GridRightMenuModel; if (model != null && model.DbClick) { DbClickItemDic.Add(cms, model); } } // 判断右键菜单是否可用 foreach (ToolStripItem cms in DbClickItemDic.Keys) { GridRightMenuModel model = DbClickItemDic[cms]; if (model != null && model.DbClick) { if (model.PrivilegeOper.Length > 1 && !model.PrivilegeOper.Contains(ERPInfo.Instance.UserName + ",")) { cms.Enabled = false; } else { if (!string.IsNullOrWhiteSpace(model.MenuCond)) { try { string cond = ReplaceHelper.ReplaceRowParam(mSelectRow, model.MenuCond); if (ParentControl != null) cond = ParentControl.ReplaceParentControlValue(cond); cms.Enabled = ReplaceHelper.EvalCond(cond); } catch (Exception) { MessageUtil.Show(ResourceKeys.SetRightMenuCondFault); } } } if (cms.Enabled) { cms.PerformClick(); } else { //MessageUtil.Show(ResourceKeys.CondtionNotSatisfiable); continue; } return; } } } } catch (Exception ex) { string Message = ErrorMessage.PromptErrorMessage(ex, Model.ModuleCode); MessageUtil.Show(Message, ex.Message); } } /// /// 说明:单元格 /// 创建人:龚宇超 /// 创建日期:2018-03-22 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The source of the event. /// The instance containing the event data. protected void OnGridViewSelectionChanged(object sender, SelectionChangedEventArgs e) { try { GridCell[] cells = this.bandedGridView.GetSelectedCells(); int[] rows = this.bandedGridView.GetSelectedRows(); // 只判断单元格数目,允许同行多单元格选中 this.pl_buttom.Visible = cells.Length > 1 && rows.Length > 1; if (this.pl_buttom.Visible) { double sum = 0, avg = 0, max = double.MinValue, min = double.MaxValue; int count = 0; foreach (GridCell cell in cells) { string cellValue = this.bandedGridView.GetRowCellValue(cell.RowHandle, cell.Column)?.ToString(); if (double.TryParse(cellValue, out double cellNumber)) { max = Math.Max(max, cellNumber); min = Math.Min(min, cellNumber); count++; sum += cellNumber; } } avg = count == 0 ? 0 : sum / count; this.lblTotal.Text = string.Format(ResourceKeys.GridTotalDisplayText, count, Math.Round(sum, 2), Math.Round(avg, 2), Math.Round(max, 2), Math.Round(min, 2)); if (this.TotalQuantity) this.lblTotal.Text = string.Format("已选中 {0} 行", rows.Length); } } catch (Exception ex) { string Message = ErrorMessage.PromptErrorMessage(ex, Model.ModuleCode); MessageUtil.Show(Message, ex.Message); } this.SelectedRows = this.bandedGridView.GetSelectedRows(); if (bandedGridView.OptionsSelection.MultiSelect == true && bandedGridView.OptionsSelection.MultiSelectMode == GridMultiSelectMode.CheckBoxRowSelect && bandedGridView.OptionsSelection.EnableAppearanceFocusedCell == false) { this.bandedGridView.UpdateSummary(); } } /// /// 说明:计算列关联字段 /// 创建人:龚宇超 /// 创建日期:2017-12-18 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The model. /// The field value. protected virtual void SetUnionValue(GridColumnModel model, string fieldValue, int RowHandle) { DataTable table = this.gridControl.DataSourceTable(); //DataRow rowItem = this.gridView.FocusedRowHandle == RowHandle || RowHandle < 0 ? this.gridView.GetFocusedDataRow() : table.Rows[RowHandle]; DataRow rowItem = table.Rows.Count == 0 || this.bandedGridView.FocusedRowHandle < 0 ? this.bandedGridView.GetFocusedDataRow() : this.bandedGridView.FocusedRowHandle == RowHandle || RowHandle < 0 ? this.bandedGridView.GetFocusedDataRow() : table.Rows[RowHandle]; //DataRow rowItem = this.gridView.GetFocusedDataRow(); string unionValues = model.UnionValues; if (rowItem != null && model != null) { unionValues = ReplaceHelper.ReplaceRowParam(rowItem, unionValues.Replace("{" + model.FieldName + "}", fieldValue)); if (this.ParentControl != null) unionValues = ParentControl.ReplaceParentControlValue(unionValues); try { string[] fields = model.UnionFields.Trim().Trim(',').Split(','); DataRow rowResult = BaseImpl.GetDataRowResult(unionValues); if (rowResult != null) { for (int i = 0; i < fields.Length; i++) { string field = fields[i]; string value = rowResult.Table.Columns.Contains(field) ? rowResult[field] + "" : null; rowItem[field] = value; } } else { // 设置为空 for (int i = 0; i < fields.Length; i++) { string field = fields[i]; rowItem[field] = DBNull.Value; } } } catch (Exception ex) { LogHelper.Instance.WriteError(ex); LogUtil.WriteError("计算列关联字段--错误-->" + unionValues, ex); } } } /// /// 说明:计算列计算公式 /// 创建人:龚宇超 /// 创建日期:2017-12-18 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The model. /// The field value. protected virtual void SetCalcValue(GridColumnModel model, string fieldValue, int RowHandle) { if (this.GridSumming) return; this.GridSumming = true; try { DataTable table = this.gridControl.DataSourceTable();//this.gridView.FocusedRowHandle == RowHandle || RowHandle < 0 ? this.gridView.GetFocusedDataRow() : table.Rows[RowHandle]; DataRow rowItem = table.Rows.Count == 0 || this.bandedGridView.FocusedRowHandle < 0 ? this.bandedGridView.GetFocusedDataRow() : this.bandedGridView.FocusedRowHandle == RowHandle || RowHandle < 0 ? this.bandedGridView.GetFocusedDataRow() : table.Rows[RowHandle]; if (rowItem != null && model != null) { foreach (GridColumn col in this.bandedGridView.Columns) { GridColumnModel colModel = col.Tag as GridColumnModel; if (colModel == null) continue; string defultValue = colModel.DefaultValue; if (colModel.FieldType == 7 && rowItem.Table.Columns.Contains(col.FieldName) && string.IsNullOrEmpty(rowItem[col.FieldName] + "") && !string.IsNullOrEmpty(colModel.DefaultValue)) { defultValue = ReplaceHelper.ReplaceUserInfo(colModel.DefaultValue); if (ParentControl != null) defultValue = ParentControl.ReplaceParentControlValue(defultValue); if (defultValue.StartsWith("@")) { defultValue = BaseImpl.GetDefaultValue(ReplaceHelper.ReplaceRowParam(rowItem, defultValue)); } if (IsNumberic(defultValue)) rowItem[col.FieldName] = defultValue;//colModel.DefaultValue; } } List calcModels = this.ColumnList.FindAll(x => !string.IsNullOrEmpty(x.CalcExpr)).OrderBy(y => y.CalcOrder).ToList(); foreach (GridColumnModel gridModel in calcModels) { // 计算顺序小于当前控件则不计算 if (gridModel.CalcOrder < model.CalcOrder) continue; if (!gridModel.FieldName.Equals(model.FieldName, StringComparison.OrdinalIgnoreCase)) { bool isTruncate = false; string calcExpr = gridModel.CalcExpr; if (calcExpr.StartsWith("@truncate:")) { calcExpr = calcExpr.Substring(10); isTruncate = true; } try { if (this.ParentControl != null) calcExpr = ParentControl.ReplaceParentControlValue(calcExpr); string result = string.Empty; if (calcExpr.StartsWith("@")) { result = BaseImpl.GetDefaultValue(ReplaceHelper.ReplaceRowParam(rowItem, calcExpr)); } else { foreach (GridColumnModel item in ColumnList) { if (calcExpr.Contains("{" + item.FieldName + "}")) { if (model.FieldType == ControlType.LabTextInt || model.FieldType == ControlType.LabCalcText || model.FieldType == ControlType.LabAccount) { if (string.IsNullOrWhiteSpace(rowItem[item.FieldName] + "")) rowItem[item.FieldName] = 0; } } //if (!string.IsNullOrEmpty(item.DataFormat)) //{ // if (model.FieldType == ControlType.LabTextInt || model.FieldType == ControlType.LabCalcText || model.FieldType == ControlType.LabAccount) // { // if (string.IsNullOrWhiteSpace(rowItem[item.FieldName] + "")) rowItem[item.FieldName] = 0; // } //} } calcExpr = ReplaceHelper.ReplaceRowParam(rowItem, calcExpr); //EvalHelper.Eval2(ReplaceHelper.ReplaceEvalCond(calcExpr)) + "" result = EvalHelper.Eval2(ReplaceHelper.ReplaceEvalCond(calcExpr)) + ""; if (result.Contains("E") || result.Contains("e")) { result = ChangeDataToD(result).ToString("0.########"); } } if (isTruncate) { result += result.Contains(".") ? "0000000000" : ".0000000000"; rowItem[gridModel.FieldName] = result.Substring(0, result.IndexOf(".")) + result.Substring(result.IndexOf("."), model.Decimals + 1); //this.gridView.SetRowCellValue(this.gridView.FocusedRowHandle, this.gridView.Columns[gridModel.FieldName], result.Substring(0, result.IndexOf(".")) + result.Substring(result.IndexOf("."), model.Decimals + 1)); } else { try { double d = 0; if (!string.IsNullOrEmpty(result) && !"NaN".Equals(result, StringComparison.OrdinalIgnoreCase) && !"非数字".Equals(result, StringComparison.OrdinalIgnoreCase) && !"undefined".Equals(result, StringComparison.OrdinalIgnoreCase) && result != "∞" && result != "-∞" && !"正无穷大".Equals(result, StringComparison.OrdinalIgnoreCase) && !"负无穷大".Equals(result, StringComparison.OrdinalIgnoreCase) && double.TryParse(result, out d)) { if (string.IsNullOrEmpty(gridModel.DataFormat)) { result = Math.Round(Convert.ToDouble(d), model.Decimals, MidpointRounding.AwayFromZero) + ""; } else { //计算后先执行保存小数位数 result = string.Format("{0:" + gridModel.DataFormat + "}", Convert.ToDecimal(result)); } if (model.FieldType == 7 && result.Contains('%')) { result = (double.Parse(result.Replace("%", "")) * 0.01).ToString(); } rowItem[gridModel.FieldName] = result; // 判断计算列有无关联值 GridColumnModel UnionModel = calcModels.FirstOrDefault(x => x.FieldName == gridModel.FieldName); if (!string.IsNullOrEmpty(UnionModel.UnionFields)) { this.SetUnionValue(UnionModel, rowItem[gridModel.FieldName] + "", RowHandle); } //this.gridView.SetRowCellValue(this.gridView.FocusedRowHandle, this.gridView.Columns[gridModel.FieldName], result); } } catch (Exception) { } } } catch (Exception ex) { LogHelper.Instance.WriteError(ex); LogUtil.WriteError("计算列计算公式--错误-->" + rowItem[gridModel.FieldName], ex); } } } } } catch (Exception ex) { LogHelper.Instance.WriteError(ex); string Message = ErrorMessage.PromptErrorMessage(ex, Model.ModuleCode); // MessageUtil.Show(Message,ex.Message); } finally { this.GridSumming = false; } } /// /// 说明:禁用控件条件 /// 创建人:龚宇超 /// 创建日期:2019-01-22 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The model. /// The field value. protected virtual void SetDisableColumn(GridColumnModel model, int rowHandler, string fieldValue) { if (model.EnableCond != string.Empty) { GridColumnModel[] columns = this.ColumnList.Where(x => x.EnableCond.Contains("{" + model.FieldName + "}")).ToArray(); DataRow rowItem = this.bandedGridView.GetDataRow(rowHandler); foreach (GridColumnModel item in columns) { try { string disableCond = ReplaceHelper.ReplaceRowParam(rowItem, item.EnableCond.Replace("{" + model.FieldName + "}", fieldValue)); string diaableType = item.DisableType; //this.gridView.Columns.ColumnByFieldName(model.FieldName).Visible = ("true".Equals(EvalHelper.Eval(ReplaceHelper.ReplaceEvalCond(disableCond)) + "", StringComparison.OrdinalIgnoreCase)); this.bandedGridView.Columns.ColumnByFieldName(model.FieldName).Visible = ("true".Equals(ValidateCond(disableCond, null) + "", StringComparison.OrdinalIgnoreCase)); } catch (Exception) { } } } } /// /// 说明:把科学计数转换为小数格式 /// 创建人:曹屹峰 /// 创建日期:2021-10-14 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// private Decimal ChangeDataToD(string strData) { Decimal dData = 0.0M; if (strData.Contains("E")) { dData = Decimal.Parse(strData, System.Globalization.NumberStyles.Float); } return dData; } /// /// 说明:检查可用条件 /// 创建人:龚宇超 /// 创建日期:2017-11-09 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The cond. /// The data row. /// true if XXXX, false otherwise. private bool ValidateCond(string cond, DataRow dataRow) { bool result = false; cond = ReplaceHelper.ReplaceRowParam(dataRow, cond); if (cond.StartsWith("@") || cond.StartsWith("!")) { result = "1".Equals(BaseImpl.GetDefaultValue(cond)); } else if (dataRow == null) { result = ReplaceHelper.EvalCond(cond); } else { result = ReplaceHelper.ReplaceRowParamCond(dataRow, cond); } return result; } /// /// 分组列获取数据 /// /// /// private void OnGridCustomDrawGroupRow(object sender, RowObjectCustomDrawEventArgs e) { try { GridGroupRowInfo GridGroupRowInfo = e.Info as GridGroupRowInfo; BandedGridColumn gridColumn = GridGroupRowInfo.Column as BandedGridColumn; if (gridColumn.Tag == null) { //动态列没有设置tag string ColumnSiftValue = string.Empty; int startindex = GridGroupRowInfo.GroupText.LastIndexOf(":"); string[] GroupText = GridGroupRowInfo.GroupText.Substring(startindex + 1).Trim().Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries); string newGroupText = GroupText[0] + ", "; GridGroupRowInfo.GroupText = GridGroupRowInfo.GroupText.Substring(0, startindex + 1) + newGroupText.TrimEnd(' ').TrimEnd(','); } else { GridColumnModel model = gridColumn.Tag as GridColumnModel; if (model == null) return; string ColumnSiftValue = string.Empty; string editValue = ControlType.IsValue(model.FieldType) ? GridGroupRowInfo.GroupValueText : GridGroupRowInfo.EditValue + ""; int startindex = GridGroupRowInfo.GroupText.LastIndexOf(":"); string[] GroupText = GridGroupRowInfo.GroupText.Substring(startindex + 1).Trim().Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries); int i = 0; string newGroupText = GroupText[0] + ", "; foreach (BandedGridColumn newColumn in this.bandedGridView.Columns) { GridColumnModel Newmodel = newColumn.Tag as GridColumnModel; if (Newmodel == null) continue; if (Newmodel.Visible && Newmodel.CanSum && !SystemInfo.Instance.GroupSpecialMode) { if (i != GroupText.Count() - 1) i++; string newGroupValue = GroupText[i].Replace(newColumn.Caption, ""); if (newColumn == HeaderColumnSift) { ColumnSiftValue = newGroupValue.Replace(",", ""); } newGroupText += newColumn.Caption + newGroupValue + ", "; } } GridGroupRowInfo.GroupText = GridGroupRowInfo.GroupText.Substring(0, startindex + 1) + newGroupText.TrimEnd(' ').TrimEnd(','); if (!string.IsNullOrWhiteSpace(editValue) && ChartTable.Columns.Count > 0) { string groupText = GridGroupRowInfo.GroupText; int endindex = groupText.LastIndexOf("行"); if (!SystemInfo.Instance.GroupSpecialMode) groupText = groupText.Substring(startindex + 1, endindex - startindex - 1).Trim(); if (!(this.ChartTable.Rows.Cast().FirstOrDefault(x => x["key"] == GridGroupRowInfo.EditValue + "") != null)) { if (BaseImpl.HasExistsTable(ResourceKeys.SettingGrouprptab)) { float vsNum = 0; bool isNum = float.TryParse(ColumnSiftValue, out vsNum); ChartTable.Rows.Add(GridGroupRowInfo.EditValue + "", groupText); if (isNum) { if (SiftEnumObj == HeaderSiftEnum.Sum) { groupText = vsNum.ToString(); } if (SiftEnumObj == HeaderSiftEnum.Avg) { groupText = (vsNum / float.Parse(groupText)) + ""; } if (SiftEnumObj == HeaderSiftEnum.Max) { //gridView.GroupSummary.Add(DevExpress.Data.SummaryItemType.Max, "数据", HeaderColumnSift, "组计:{0}"); } if (SiftEnumObj == HeaderSiftEnum.Min) { } } string tempSql = string.Format(@"insert into {3}(GroupName,GroupAmount,OperAtorId) values('{0}','{1}','{2}');", editValue, groupText, ERPInfo.Instance.UserId, ResourceKeys.SettingGrouprptab); SqlHelper.ExecuteNonQuery(tempSql); } } } } } catch (Exception ex) { string Message = ErrorMessage.PromptErrorMessage(ex, Model.ModuleCode); MessageUtil.Show(Message, ex.Message); } } /// /// 点击标题行排序后,默认选中第一行 /// /// /// private void BandedGridView_EndSorting(object sender, EventArgs e) { this.bandedGridView.MoveFirst(); // 将焦点行移动到第一行 this.bandedGridView.FocusedRowHandle = 0;// 确保第一行被聚焦 } /// /// 水平滚动条位置改变 /// /// /// private void OnBandedLeftCoordChanged(object sender, EventArgs e) { if (OnLeftCoordCallback != null) { OnLeftCoordCallback(sender, e); } } /// /// 设置数值的编辑格式 /// /// /// private void GridView_ShowingEditor(object sender, CancelEventArgs e) { GridColumn gridColumn = bandedGridView.FocusedColumn; if (gridColumn != null && gridColumn.Tag != null) { GridColumnModel model = (GridColumnModel)gridColumn.Tag; if (model.FormatEditBox && (model.FieldType == ControlType.LabTextInt || model.FieldType == ControlType.LabCalcText || model.FieldType == ControlType.LabAccount) && gridColumn.RealColumnEdit != null && !gridColumn.RealColumnEdit.EditFormat.FormatString.Equals(model.DataFormat)) { gridColumn.RealColumnEdit.EditFormat.FormatType = DevExpress.Utils.FormatType.Numeric; gridColumn.RealColumnEdit.EditFormat.FormatString = model.DataFormat; } } } } }