/******************************
* 说明:多表头表格
* 创建人:龚宇超
* 创建日期: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