/*******************************************************************************
* Copyright(c) 2012 dongke All rights reserved. / Confidential
* 类的信息:
* 1.程序名称:dkDataGridView.cs
* 2.功能描述:扩展的DataGridView控件
* 编辑履历:
* 作者 日期 版本 修改内容
* 欧阳涛 2012/06/07 1.00 新建
* 周兴 2012/07/24 1.00 扩展复合型表头和树形结构
*******************************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
using Dongke.IBOSS.Framework.DKResources;
using Dongke.IBOSS.Framework.Library;
namespace Dongke.IBOSS.Framework.Controls
{
///
/// 剪贴板的种类枚举
///
public enum ClipboardType
{
InnerAndDisp,
InnerOnly
}
///
/// 过滤类型
///
public enum FilterType
{
///
/// 全部匹配
///
Equal,
///
/// 全部不匹配
///
NotEqual,
///
/// 模糊匹配
///
Like,
///
/// 不模糊匹配
///
NotLike
}
public partial class dkDataGridView : DataGridView
{
#region 枚举类型
///
/// CELL的背景色区分
///
[Flags]
public enum CellBackColorFlags
{
///
/// 无背景色
///
None = 0,
///
/// 只读背景色
///
ReadOnlyBackColor = 1,
///
/// 内容有变化的背景色
///
ChangesBackColor = 2,
///
/// 所有全部背景色
///
All = ReadOnlyBackColor | ChangesBackColor
}
///
/// 右键菜单选项
///
[Flags]
public enum ContextMenuVisibleFlags
{
///
/// 无
///
None = 0,
///
/// 过滤
///
Refine = 1,
///
/// 输出Excel文件
///
FileOut = 2,
///
/// 打印
///
Print = 3,
///
/// 所有菜单
///
All = Refine | FileOut
}
#endregion
#region 委托
public delegate void CsvConveringEventHandler(object sender, CsvConvertingEventArgs e);
#endregion
#region 事件
public event CsvConveringEventHandler CsvConverting = null;
public event EventHandler MouseClickOnSpace;
public event EventHandler RowsHeaderClick;
#endregion
#region 成员变量
private ContextMenuStrip _ctxColumnHeader;
private ContextMenuStrip _ctxCell;
private ToolStripMenuItem _mnuFrozen = new ToolStripMenuItem();
private ToolStripRefine _mnuRefine = new ToolStripRefine(); // 条件过滤
private ToolStripMenuItem _mnuFilter = new ToolStripMenuItem(); // 过滤
private ToolStripMenuItem _mnuFilterExcept = new ToolStripMenuItem(); // 除外过滤
private ToolStripMenuItem _mnuUnfilter = new ToolStripMenuItem(); // 清除过滤
private ToolStripMenuItem _mnuOutputFile = new ToolStripMenuItem(); // 输出csv
private ToolStripMenuItem _mnuOutputFileXls = new ToolStripMenuItem(); // 输出excel
private ToolStripMenuItem _mnuPrint = new ToolStripMenuItem(); // 打印
private ToolStripMenuItem _mnuDelete = new ToolStripMenuItem(); // 删除
private ContextMenuVisibleFlags _contextMenuVisibleFlag = ContextMenuVisibleFlags.All;
private Label labelHideFocus; // 取得焦点的Lable
private System.ComponentModel.IContainer components;
private bool _isAllowUserToModifyRows = true;
private bool _isAllowUserToSortRows = true;
private CellBackColorFlags _cellBackColorFlag = CellBackColorFlags.None; // 背景颜色的设定标识
private Color _cellBackColorNochanged = Color.FromArgb(255, 255, 255); // 无变化时Cell的背景颜色
private Color _cellBackColorReadOnly = SystemColors.Control; // 只读时Cell的背景颜色
private Color _cellBackColorAdded = Color.FromArgb(255, 230, 230); // 新建时Cell的背景颜色
private Color _cellBackColorModified = Color.FromArgb(210, 220, 255); // 编辑时Cell的背景颜色
private Color _cellBackColorDeleted = Color.FromArgb(240, 255, 220); // 删除时Cell的背景颜色
private bool _isDispRowCount = true; // 是否显示总行数信息
private int[] _selectCellRowCol = { 0, 0 }; // 选择行的行号和列号
private bool _isFrozen = false; // 冻结·解冻标识
private bool _isChildDGV = false;
private string _viewRowFilterString = string.Empty;
private string _sortOrderColumnName;
private string _sortColumnName = string.Empty;
private SortOrder _sortOrderType = SortOrder.None;
private bool _isClearSelected = false;
private bool _isShowDelete = false;
private bool _isCanDelete = false;
private int _gridRowIndex = 0;
private int _gridColumnindex = 0;
private TreeView[] _columnTreeView;
private ArrayList _columnList = new ArrayList();
private int _cellHeight = 25;
private bool _hscrollRefresh = false;
private int _columnDeep = 1;
private TreeGridNode _root;
private TreeGridColumn _expandableColumn;
internal ImageList _imageList;
private bool _virtualNodes = false;
private bool _isHasNode = false;
private string _nodeColumnName = string.Empty;
private bool _inExpandCollapse = false;
internal bool _inExpandCollapseMouseCapture = false;
private Control hideScrollBarControl;
private bool _showLines = true;
private string _dynamicColumnName = string.Empty;
private string[] _childNodeColumnName = null;
private string[] _childNodeColumnText = null;
private DataTable dt;//绑定的表
private string filter = "";//filter字符串
public bool _isOpenTotalRow = false;
private DataGridViewColumnInfo[] _columnInfos = null;
#endregion
#region 公开属性
[System.ComponentModel.Browsable(true)]
[System.ComponentModel.DefaultValue(false)]
[System.ComponentModel.Description("常选择。")]
public bool IsClearSelected
{
get
{
return _isClearSelected;
}
set
{
_isClearSelected = value;
}
}
[System.ComponentModel.DefaultValue(false)]
[System.ComponentModel.Description("删除标识。")]
public bool IsShowDelete
{
get
{
return _isShowDelete;
}
set
{
_isShowDelete = value;
}
}
[System.ComponentModel.DefaultValue(false)]
[System.ComponentModel.Description("允许删除标识。")]
public bool IsCanDelete
{
get
{
return _isCanDelete;
}
set
{
_isCanDelete = value;
}
}
[System.ComponentModel.Browsable(true)]
[System.ComponentModel.DefaultValue(false)]
[System.ComponentModel.Description("设定或者获取可否允许用户编辑行。")]
public bool AllowUserToModifyRows
{
get
{
return _isAllowUserToModifyRows;
}
set
{
_isAllowUserToModifyRows = value;
}
}
[System.ComponentModel.Browsable(true)]
[System.ComponentModel.DefaultValue(true)]
[System.ComponentModel.Description("设定或者获取可否允许用户排序。")]
public bool AllowUserToSortRows
{
get
{
return _isAllowUserToSortRows;
}
set
{
_isAllowUserToSortRows = value;
foreach (DataGridViewColumn column in this.Columns)
{
column.SortMode =
(_isAllowUserToSortRows) ? DataGridViewColumnSortMode.Automatic :
DataGridViewColumnSortMode.NotSortable;
}
}
}
[System.ComponentModel.Browsable(true)]
[System.ComponentModel.DefaultValue("")]
[System.ComponentModel.Description("设定或者获取排序的列名。")]
public string SortOrderColumnName
{
get
{
return _sortOrderColumnName;
}
set
{
_sortOrderColumnName = value;
}
}
[System.ComponentModel.Browsable(true)]
[System.ComponentModel.DefaultValue(CellBackColorFlags.None)]
[System.ComponentModel.Description("设定或者获取Cell背景色设定标识。")]
public CellBackColorFlags CellBackColorFlag
{
get
{
return _cellBackColorFlag;
}
set
{
_cellBackColorFlag = value;
}
}
[System.ComponentModel.Browsable(true)]
[System.ComponentModel.DefaultValue(typeof(Color), "255, 255, 255")]
[System.ComponentModel.Description("设定或者获取Cell没有改变时的背景颜色。")]
public Color CellBackColorNochanged
{
get
{
return _cellBackColorNochanged;
}
set
{
_cellBackColorNochanged = value;
}
}
[System.ComponentModel.Browsable(true)]
[System.ComponentModel.DefaultValue(typeof(Color), "SystemColors.Control")]
[System.ComponentModel.Description("设定或者获取只读Cell的背景颜色。")]
public Color CellBackColorReadOnly
{
get
{
return _cellBackColorReadOnly;
}
set
{
_cellBackColorReadOnly = value;
}
}
[System.ComponentModel.Browsable(true)]
[System.ComponentModel.DefaultValue(typeof(Color), "255, 230, 230")]
[System.ComponentModel.Description("设定或者获取新建Cell的背景颜色。")]
public Color CellBackColorAdded
{
get
{
return _cellBackColorAdded;
}
set
{
_cellBackColorAdded = value;
}
}
[System.ComponentModel.Browsable(true)]
[System.ComponentModel.DefaultValue(typeof(Color), "210, 220, 255")]
[System.ComponentModel.Description("设定或者获取编辑过Cell的背景颜色。")]
public Color CellBackColorModified
{
get
{
return _cellBackColorModified;
}
set
{
_cellBackColorModified = value;
}
}
[System.ComponentModel.Browsable(true)]
[System.ComponentModel.DefaultValue(typeof(Color), "240, 255, 220")]
[System.ComponentModel.Description("设定或者获取删除的Cell背景颜色。")]
public Color CellBackColorDeleted
{
get
{
return _cellBackColorDeleted;
}
set
{
_cellBackColorDeleted = value;
}
}
[System.ComponentModel.Browsable(true)]
[System.ComponentModel.Description("设定或者获取右键菜单的内容。")]
public ContextMenuVisibleFlags ContextMenuVisible
{
get
{
return _contextMenuVisibleFlag;
}
set
{
_contextMenuVisibleFlag = value;
}
}
///
/// 设置输入单元格的颜色
///
public bool IsSetInputColumnsColor
{
set
{
if (DataSource != null && !this.ReadOnly && this.Enabled)
{
for (int i = 0; i < this.Rows.Count; i++)
{
if (!this.Rows[i].ReadOnly)
{
for (int j = 0; j < this.Columns.Count; j++)
{
if (!this.Rows[i].Cells[this.Columns[j].Name].ReadOnly)
{
this.Rows[i].Cells[this.Columns[j].Name].Style.BackColor
= ColorTranslator.FromHtml(Constant.ALLOW_MODIFY_AREA_BACKGROUND_COLOR);
}
else
{
this.Rows[i].Cells[this.Columns[j].Name].Style.BackColor = Color.White;
}
}
}
}
}
}
}
///
/// 设定或者获取当前DataTable
///
public DataTable CurrentDataTable
{
get
{
return DataConvert.ToDataTable(this.DataSource, this.DataMember);
}
}
[System.ComponentModel.Browsable(true)]
[System.ComponentModel.DefaultValue(typeof(bool), "true")]
[System.ComponentModel.Description("设定或者获取是否显示行数选项。")]
public bool IsDispRowCount
{
get
{
return _isDispRowCount;
}
set
{
_isDispRowCount = value;
}
}
[Description("设置多维表头时,设置动态列")]
public string DynamicColumnName
{
get
{
return this._dynamicColumnName;
}
set
{
this._dynamicColumnName = value;
}
}
[Description("设置多维表头时,设置的子列名称")]
public string[] ChildNodeColumnName
{
get
{
return this._childNodeColumnName;
}
set
{
this._childNodeColumnName = value;
}
}
[Description("设置多维表头时,设置的子列显示名称")]
public string[] ChildNodeColumnText
{
get
{
return this._childNodeColumnText;
}
set
{
this._childNodeColumnText = value;
}
}
[Description("是否设置节点")]
public bool HasNode
{
get
{
return this._isHasNode;
}
set
{
this._isHasNode = value;
}
}
public new object DataSource
{
get
{
return base.DataSource;
}
set
{
try
{
if (value != null)
{
dt = (DataTable)value;
// 设置列头显示的形式
if (this.RowHeadersVisible)
{
this.RowHeadersWidth = 50;
if (dt.Rows.Count > 999)
{
this.RowHeadersWidth += (dt.Rows.Count.ToString().Length - 3) * 15;
}
}
}
else
{
this.RowHeadersWidth = 50;
// 如果数据源为空,并且是打开了合计行的,需要重新计算合计行的值
if (_isOpenTotalRow && base.DataSource != null)
{
dt = ((DataTable)base.DataSource).Clone();
if (this.ReadOnly && this.AllowUserToAddRows)
{
this.AllowUserToAddRows = false;
}
//CountTotalRow();
}
//if (_isOpenTotalRow && base.DataSource == null)
//{
// CountTotalRow();
//}
if (_isOpenTotalRow)
{
ClearTotalRowData();
}
}
// 根据列名去设置树形结构
if (HasNode && value != null && !string.IsNullOrEmpty(NodeColumnName))
{
this.Nodes.Clear();
DataRow[] dataRows = null;
TreeGridNode node = null;
DataRow[] dataRowsTmp = null;
DataTable dataTable = (DataTable)value;
SortedList sortedlist = new SortedList();
dataRows = dataTable.Select(" ParentID = 0");
for (int i = 0; i < dataRows.Length; i++)
{
node = this.Nodes.Add(dataRows[i], dataTable.Columns, this.Columns, sortedlist, out sortedlist);
dataRowsTmp = dataTable.Select(" ParentID = " + dataRows[i][NodeColumnName]);
InitNode(dataTable, node, sortedlist, dataRowsTmp);
}
// Control when edit occurs because edit mode shouldn't start when expanding/collapsing
//this.EditMode = DataGridViewEditMode.EditProgrammatically;
this.RowTemplate = new TreeGridNode() as DataGridViewRow;
// This sample does not support adding or deleting rows by the user.
this.AllowUserToAddRows = false;
this.AllowUserToDeleteRows = false;
}
// 动态生成多维表头(目前只支持2维)
else if (!string.IsNullOrEmpty(DynamicColumnName) && value != null
&& ChildNodeColumnName != null && ChildNodeColumnName.Length > 0)
{
DataTable dataTable = (DataTable)value;
ArrayList dynamicnames = new ArrayList();
for (int i = 0; i < dataTable.Rows.Count; i++)
{
if (!dynamicnames.Contains(dataTable.Rows[i][DynamicColumnName]))
{
dynamicnames.Add(dataTable.Rows[i][DynamicColumnName]);
}
}
DataTable tmpTable = LoadColumnHeaderTree(dynamicnames);
this.ColumnDeep = 2;
this.ColumnHeadersHeightSizeMode =
DataGridViewColumnHeadersHeightSizeMode.EnableResizing;
this.ScrollBars = ScrollBars.Both;
//base.DataSource = value;
tmpTable = BindData(dataTable, tmpTable, dynamicnames);
this.RowCount = tmpTable.Rows.Count;
base.DataSource = tmpTable;
}
else
{
base.DataSource = value;
this.ClearSelection();
}
// 设置交替行颜色
if (IsOpenMergeCellFlag )
{
this.SetDataGridViewRowColor();
}
}
catch (Exception ex)
{
throw ex;
}
}
}
[Browsable(false)]
[DefaultValue(false)]
public bool IsChildDGV
{
get
{
return _isChildDGV;
}
set
{
_isChildDGV = value;
}
}
[Browsable(false)]
public string ViewRowFilter
{
get
{
return _viewRowFilterString;
}
set
{
_viewRowFilterString = value;
}
}
public int CellHeight
{
get
{
return _cellHeight;
}
set
{
_cellHeight = value;
}
}
public bool RefreshAtHscroll
{
get
{
return _hscrollRefresh;
}
set
{
_hscrollRefresh = value;
}
}
[Description("设置或获得合并表头数的深度")]
public int ColumnDeep
{
get
{
if (this.Columns.Count == 0)
{
_columnDeep = 1;
}
this.ColumnHeadersHeight = _cellHeight * _columnDeep;
return _columnDeep;
}
set
{
if (value < 1)
{
_columnDeep = 1;
}
else
{
_columnDeep = value;
}
this.ColumnHeadersHeight = _cellHeight * _columnDeep;
}
}
[Description("添加合并式单元格绘制的所需要的节点对象")]
public TreeView[] ColumnTreeView
{
get
{
return _columnTreeView;
}
set
{
//if (_columnTreeView != null)
//{
// for (int i = 0; i <=_columnTreeView.Length -1; i++)
// {
// _columnTreeView[i].Dispose();
// }
//}
_columnTreeView = value;
}
}
[Description("设置添加的字段数的相关属性")]
public TreeView ColumnTreeViewNode
{
get
{
if (_columnTreeView != null && _columnTreeView.Length > 0 && _columnTreeView[0] != null)
{
return _columnTreeView[0];
}
return null;
}
}
public ArrayList ColumnList
{
get
{
if (_columnTreeView == null)
{
return null;
}
if (_columnTreeView[0] == null)
{
return null;
}
if (_columnTreeView[0].Nodes == null)
{
return null;
}
if (_columnTreeView[0].Nodes.Count == 0)
{
return null;
}
_columnList.Clear();
GetColumnNodes(_columnList, _columnTreeView[0].Nodes[0], false);
return _columnList;
}
}
public new DataGridViewRowCollection Rows
{
get { return base.Rows; }
}
public new DataGridViewRow RowTemplate
{
get { return base.RowTemplate; }
set { base.RowTemplate = value; }
}
[DefaultValue(true)]
public bool ShowLines
{
get { return this._showLines; }
set
{
if (value != this._showLines)
{
this._showLines = value;
this.Invalidate();
}
}
}
public new int RowCount
{
get
{
return base.RowCount;
}
set
{
base.RowCount = value;
}
}
[Description("是否能导出excel")]
[DefaultValue(true)]
public bool IsExportFlag
{
set;
get;
}
[DefaultValue(true)]
public bool IsProcessRightFlag
{
get;
set;
}
[DefaultValue(false)]
public bool IsSelectGoodsFlag
{
get;
set;
}
///
/// 需要进行合计的列,如果没有,就是所有的可以的合计的列都合计
///
public List TotalSumColumns
{
get;
set;
}
///
/// 是否自动计算合计行,默认是自动
///
public bool IsAutoCountSum
{
get;
set;
}
///
/// 是否有小计,在有合计行时使用
///
public bool IsSubTotalFlag
{
get;
set;
}
///
/// 是否点了自适应列宽
///
public bool IsAutoResizeColumns
{
get;
set;
}
///
/// 是否点击F12隐藏
///
public bool IsClickF12
{
get;
set;
}
[Description("设置树形结构时,需要设置关系的主键ID名称")]
public string NodeColumnName
{
get
{
return this._nodeColumnName;
}
set
{
this._nodeColumnName = value;
}
}
public TreeGridNodeCollection Nodes
{
get
{
return this._root.Nodes;
}
}
public TreeGridNode CurrentRowT
{
get
{
return base.CurrentRow as TreeGridNode;
}
}
[Description("Causes nodes to always show as expandable. Use the NodeExpanding event to add nodes.")]
public bool VirtualNodes
{
get { return _virtualNodes; }
set { _virtualNodes = value; }
}
public TreeGridNode CurrentNode
{
get
{
return this.CurrentRowT;
}
}
public ImageList ImageList
{
get { return this._imageList; }
set
{
this._imageList = value;
//TODO: should we invalidate cell styles when setting the image list?
}
}
///
/// 用合计的值进行计算值 的列
///
public string TotalCountName
{
get;
set;
}
///
/// 用合计的值进行计算 的公式
///
public string TotalCountFormula
{
get;
set;
}
///
/// 需要合并的列(周兴 2015-12-6 修改)
///
public List MergeColumnNames
{
get;
set;
}
///
/// 需要合并的列(明细,必须在上面属性中也存在,这个属性类似于子属性)(周兴 2015-12-6 修改)
///
public List MergeDetailColumnNames
{
get;
set;
}
///
/// 合并单元格时需要唯一列(比如SalesID,不同的SalesID的是不允许合并在一起的
///
public string MergeOnlyColumn
{
get;
set;
}
///
/// 合并单元格时需要唯一列(子列)(比如DetailID,相同SalesID的不同DetailID也是不允许合并的
///
public string MergeDetailOnlyColumn
{
get;
set;
}
///
/// 合并单元格时需要唯一列(子列)(比如DetailID,相同SalesID的不同DetailID也是不允许合并的
///
public string MergeDDetailOnlyColumn
{
get;
set;
}
///
/// 需要合并的列(明细,必须在上面属性中也存在,这个属性类似于子属性)(周兴 2015-12-6 修改)
///
public List MergeDDetailColumnNames
{
get;
set;
}
///
/// 是否开启合并单元格
///
public bool IsOpenMergeCellFlag
{
get;
set;
}
///
/// 是否打印
///
public bool IsPrintFlag
{
get;
set;
}
#endregion
#region 构造函数
public dkDataGridView()
{
InitializeComponent();
this.Tag = true;
IsProcessRightFlag = true;
IsSelectGoodsFlag = false;
IsAutoCountSum = true;
IsExportFlag = true;
IsAutoResizeColumns = false;
IsSubTotalFlag = false;
this.Rows.CollectionChanged +=
new System.ComponentModel.CollectionChangeEventHandler(Rows_CollectionChanged);
this._mnuFrozen.Name = "mnuFrozen";
this._mnuFrozen.Size = new System.Drawing.Size(143, 22);
this._mnuFrozen.Text = DKResources.ControlsTips.DK_DataGridView_Frozen;
this._mnuFrozen.ToolTipText = DKResources.ControlsTips.TOOLTIP_DataGridView_M001;
this._mnuRefine.ToolTipText = DKResources.ControlsTips.TOOLTIP_DataGridView_M002;
this._mnuFilter.Name = "mnuFilter";
this._mnuFilter.Size = new System.Drawing.Size(118, 22);
this._mnuFilter.Text = DKResources.ControlsTips.DK_DataGridView_Filter;
this._mnuFilter.ToolTipText = DKResources.ControlsTips.TOOLTIP_DataGridView_M003;
this._mnuFilterExcept.Name = "mnuFilterExcept";
this._mnuFilterExcept.Size = new System.Drawing.Size(143, 22);
this._mnuFilterExcept.Text = DKResources.ControlsTips.DK_DataGridView_FilterExcept;
this._mnuFilterExcept.ToolTipText = DKResources.ControlsTips.TOOLTIP_DataGridView_M004;
this._mnuUnfilter.Name = "mnuUnfilter";
this._mnuUnfilter.Size = new System.Drawing.Size(143, 22);
this._mnuUnfilter.Text = DKResources.ControlsTips.DK_DataGridView_Unfilter;
this._mnuUnfilter.ToolTipText = DKResources.ControlsTips.TOOLTIP_DataGridView_M005;
this._mnuOutputFile.Name = "mnuOutputFile";
this._mnuOutputFile.Size = new System.Drawing.Size(143, 22);
this._mnuOutputFile.Text = DKResources.ControlsTips.DK_DataGridView_OutputFile;
// 周兴 2016-7-22 增加 输出excel
this._mnuOutputFileXls.Name = "mnuOutputFileXls";
this._mnuOutputFileXls.Size = new System.Drawing.Size(143, 22);
this._mnuOutputFileXls.ToolTipText = DKResources.ControlsTips.TOOLTIP_DataGridView_M008;
this._mnuOutputFileXls.Text = DKResources.ControlsTips.DK_DataGridView_OutputFileXLs;
this._mnuDelete.Name = "mnuDelete";
this._mnuDelete.Size = new System.Drawing.Size(143, 22);
this._mnuDelete.Text = DKResources.ControlsTips.DK_DataGridView_DeleteRow;
this._mnuDelete.ToolTipText = DKResources.ControlsTips.TOOLTIP_DataGridView_M006;
this._mnuPrint.Name = "mnuPrint";
this._mnuPrint.Size = new System.Drawing.Size(143, 22);
this._mnuPrint.Text = DKResources.ControlsTips.DK_DataGridView_Print;
this._mnuPrint.ToolTipText = DKResources.ControlsTips.TOOLTIP_DataGridView_M007;
// 事件
this._mnuRefine.RefineTextFixed += new EventHandler(mnuRefine_RefineTextFixed);
this._mnuFilter.Click += new EventHandler(mnuFilter_Click);
this._mnuFilterExcept.Click += new EventHandler(mnuFilterExcept_Click);
this._mnuUnfilter.Click += new EventHandler(mnuUnfilter_Click);
this._mnuOutputFile.Click += new EventHandler(mnuOutputFile_Click);
this._mnuOutputFileXls.Click += new EventHandler(mnuOutputFileXls_Click);
this._mnuFrozen.Click += new EventHandler(mnuFrozen_Click);
this._mnuDelete.Click += new EventHandler(mnuDelete_Click);
this._mnuPrint.Click += new EventHandler(mnuPrint_Click);
//// Control when edit occurs because edit mode shouldn't start when expanding/collapsing
//this.EditMode = DataGridViewEditMode.EditProgrammatically;
//this.RowTemplate = new TreeGridNode() as DataGridViewRow;
//// This sample does not support adding or deleting rows by the user.
//this.AllowUserToAddRows = false;
//this.AllowUserToDeleteRows = false;
this.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
this.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing;
this.RowHeadersWidth = 50;
this._root = new TreeGridNode(this);
this._root.IsRoot = true;
//// Ensures that all rows are added unshared by listening to the CollectionChanged event.
//base.Rows.CollectionChanged += delegate(object sender, System.ComponentModel.CollectionChangeEventArgs e) { };
}
#endregion
#region 公开方法/函数
public CurrencyManager GetCurrencyManager()
{
if (this.DataSource == null)
{
return null;
}
return this.BindingContext[this.DataSource, this.DataMember] as CurrencyManager;
}
public DataTable GetDataTable()
{
CurrencyManager bindingManager = GetCurrencyManager();
if (bindingManager == null)
{
return null;
}
DataView dataView = bindingManager.List as DataView;
if (dataView == null)
{
return null;
}
return dataView.Table;
}
public DataRowView GetDataRowView(int viewRowIndex)
{
if (viewRowIndex < 0)
{
return null;
}
if (this.DataSource == null)
{
return null;
}
try
{
CurrencyManager bindingManager = GetCurrencyManager();
if (bindingManager != null)
{
if (viewRowIndex < bindingManager.List.Count)
{
return (bindingManager.List[viewRowIndex] as DataRowView);
}
}
}
catch (Exception ex)
{
Debug.Assert(false, "Error", ex.Message);
}
return null;
}
public DataRow GetDataRow(int viewRowIndex)
{
DataRowView rowView = GetDataRowView(viewRowIndex);
if (rowView == null)
{
return null;
}
if (rowView.Row == null)
{
return null;
}
return rowView.Row;
}
public int GetDataRowIndex(int viewRowIndex)
{
DataRow row = GetDataRow(viewRowIndex);
if (row == null)
{
return -1;
}
return row.Table.Rows.IndexOf(row);
}
public int GetViewColumnIndex(string dataColumnName)
{
for (int i = 0; i < this.Columns.Count; i++)
{
DataGridViewColumn column = this.Columns[i];
string dataPropartyName = column.DataPropertyName;
if (dataColumnName.Equals(dataPropartyName))
{
return i;
}
}
return -1;
}
public void OutputFile()
{
OutputFile(true);
}
public void SetFrozen()
{
int selectRow = _gridRowIndex;
int selectCol = _gridColumnindex;
bool isSelectSameCell = true;
// 清除冻结
if (0 < this.Rows.Count)
{
this.Rows[0].Frozen = false;
}
if (0 < this.Columns.Count)
{
this.Columns[0].Frozen = false;
}
// 是否选择了同一个单元格
isSelectSameCell = IsSelectSameCell(selectRow, selectCol);
if (isSelectSameCell && _isFrozen)
{
_isFrozen = false;
return;
}
_isFrozen = false;
if (0 < selectRow)
{
// 行冻结处理
this.Rows[selectRow - 1].Frozen = true;
_isFrozen = true;
}
if (0 < selectCol)
{
// 列冻结处理
//this.Columns[selectCol - 1].Frozen = true;
if (this.ColumnTreeViewNode != null && this.ColumnTreeViewNode.Nodes.Count > 0 && _columnDeep > 1)
{
// 说明是多维表头
foreach (TreeNode node in this.ColumnTreeViewNode.Nodes)
{
if (this.Columns[selectCol].Name.Equals(node.Name))
{
this.Columns[node.Index].Frozen = true;
break;
}
else
{
if (node.Nodes != null)
{
foreach (TreeNode childNode in node.Nodes)
{
if (this.Columns[selectCol].Name.Equals(childNode.Name))
{
this.Columns[node.LastNode.Name].Frozen = true;
return;
}
}
}
}
}
}
else
{
foreach (DataGridViewColumn column in this.Columns)
{
if (selectCol == column.Index)
{
this.Columns[column.DisplayIndex - 1].Frozen = true;
break;
}
}
}
if (_isOpenTotalRow)
{
_columnInfos = GetDataGridViewColumnInfos();
if (_columnInfos != null)
{
this.HorizontalScrollingOffset = 0;
for (int i = 0; i < _columnInfos.Length; i++)
{
if (_columnInfos[i].Visible)
{
NewText(_columnInfos[i].DataPropertyName, i);
}
}
CountTotalRow();
}
}
_isFrozen = true;
}
// 当前选择的行号和列号
_selectCellRowCol[0] = selectRow;
_selectCellRowCol[1] = selectCol;
}
public void OutputFile(bool isAllCells)
{
try
{
SaveFileDialog dialog = new SaveFileDialog();
dialog.Filter = "csv file (*.csv)|*.csv";
if (dialog.ShowDialog() == DialogResult.OK)
{
string csv = ToCsvString(true, false, true, isAllCells);
if (!string.IsNullOrEmpty(csv))
{
System.IO.FileInfo fileInfo = new System.IO.FileInfo(dialog.FileName);
System.IO.FileStream fileStream = fileInfo.Create();
Byte[] buffer = System.Text.Encoding.GetEncoding("GB2312").GetBytes(csv);
fileStream.Write(buffer, 0, buffer.Length);
fileStream.Dispose();
}
}
}
catch (Exception ex)
{
//
}
}
///
/// 导出excel
///
public void OutputFileXls()
{
try
{
string sheetName = string.Empty;
string fileName = string.Empty;
bool flag = true;
Control control = this.Parent;
while (flag)
{
if (control != null && control is TabPage)
{
sheetName = control.Text;
}
if (control != null && control is Form)
{
fileName = control.Text;
if (string.IsNullOrEmpty(sheetName))
{
sheetName = fileName;
}
flag = false;
}
control = control.Parent;
if (control == null)
{
flag = false;
}
}
TreeView tv = null;
if (_columnTreeView != null && _columnTreeView.Length > 0)
{
tv = _columnTreeView[0];
}
Common.Instance.ExportExcel(this, tv, null, fileName, fileName, this.Font, "", this.Font, "", sheetName, true, true);
}
catch (Exception ex)
{
//
}
}
public string GetColumnIndex(int columnIndex)
{
if (_columnInfos == null)
{
_columnInfos = GetDataGridViewColumnInfos();
}
if (columnIndex > _columnInfos.Length -1 )
{
return string.Empty;
}
return _columnInfos[columnIndex].DataPropertyName;
}
public string ToCsvString(bool isHeaderFirstRow, bool isTsv,
bool isFormattedValue, bool isAllCells)
{
if (this.CurrentCell != null)
{
if (this.CurrentCell.IsInEditMode && !(
this.CurrentCell is DataGridViewCheckBoxCell))
{
return null;
}
}
if (CurrentDataTable == null)
{
return null;
}
DataTable table = new DataTable();
List columnIndexList;
int rowIndexMin, rowIndexMax;
DataGridViewColumnInfo[] columnInfo = null;
if (isAllCells)
{
columnIndexList = new List();
columnInfo = this.GetDataGridViewColumnInfos();
//for (int i = 0; i < columnInfo.Length; i++)
//{
// columnIndexList.Add(i);
//}
//for (int i = 0; i < this.Columns.Count; i++)
//{
// if (this.Columns[i].Visible)
// {
// columnIndexList.Add(this.Columns[i].DisplayIndex);
// }
//}
rowIndexMin = 0;
rowIndexMax = this.Rows.Count - 1;
if (this.AllowUserToAddRows)
{
rowIndexMax -= 1;
}
}
else
{
GetSelectedRange(out columnIndexList, out rowIndexMin, out rowIndexMax);
}
List invalidColumnList = new List();
//foreach (int columnIndex in columnIndexList)
//{
// string columnName = this.Columns[columnIndex].Name;
// DataGridViewColumn column = this.Columns[columnName];
// if (column == null)
// {
// invalidColumnList.Add(columnIndex);
// continue;
// }
// if (!isFormattedValue && column.CellType.Name ==
// "DataGridViewSearchFileBoxCellEx")
// {
// invalidColumnList.Add(columnIndex);
// continue;
// }
// DataColumn dcolColumn = new DataColumn(column.Name);
// dcolColumn.Caption = column.HeaderText;
// table.Columns.Add(dcolColumn);
//}
//foreach (int columnIndex in invalidColumnList)
//{
// columnIndexList.Remove(columnIndex);
//}
if (columnInfo != null)
{
for (int i = 0; i < columnInfo.Length; i++)
{
DataColumn dcolColumn = new DataColumn(columnInfo[i].ColumnName);
dcolColumn.Caption = columnInfo[i].TreeColumnText;
table.Columns.Add(dcolColumn);
}
}
DataRow drowRow;
for (int i = rowIndexMin; i <= rowIndexMax; i++)
{
drowRow = table.NewRow();
DataGridViewRow rowView = this.Rows[i];
if (rowView != null)
{
int j = 0;
for (int k = 0; k < columnInfo.Length; k++)
{
DataGridViewCell cell = rowView.Cells[columnInfo[k].ColumnName];
object value;
if (isFormattedValue)
{
value = cell.FormattedValue;
}
else
{
value = cell.Value;
}
// 周兴 2015-11-19 如果前几个都是0,导出csv就会消失
if ("String".Equals(cell.ValueType.Name) && (cell.Value + "").StartsWith("0"))
{
value = ((char)(9)).ToString() + value;
}
//周兴 2016-3-22 修改
if ("String".Equals(cell.ValueType.Name) && (cell.Value + "").IndexOf("-") > 0)
{
value = ((char)(9)).ToString() + value;
}
//if (!string.IsNullOrEmpty(value + "") && value.ToString().StartsWith("-"))
//{
// value = "'" + value;
//}
CsvConvertingEventArgs e = new CsvConvertingEventArgs(k, value);
OnCsvCoverting(e);
drowRow[j] = e.Value;
j++;
}
table.Rows.Add(drowRow);
}
}
// 周兴 2015-11-24 如果有合计把合计行也显示进来
if (_isOpenTotalRow)
{
try
{
drowRow = table.NewRow();
TextBox tempTB;
bool flag = false;
for (int k = 0; k < columnInfo.Length; k++)
{
tempTB = findTextBox("txt" + columnInfo[k].DataPropertyName);
if (tempTB != null && table.Columns.Contains(columnInfo[k].DataPropertyName))
{
if (!flag && "".Equals(tempTB.Text))
{
drowRow[columnInfo[k].DataPropertyName] = "合计";
flag = true;
}
else
{
drowRow[columnInfo[k].DataPropertyName] = tempTB.Text;
}
}
}
table.Rows.Add(drowRow);
}
catch (Exception ex)
{
}
}
// DataTable情報をcsv形式に変換
Char delim = ',';
if (isTsv)
{
delim = '\t';
}
return CsvManager.ToString(table, isHeaderFirstRow, delim, '\"');
}
///
/// 绘制合并表头
///
/// 合并表头节点
/// 绘图参数集
/// 节点深度
public void PaintUnitHeader(TreeNode node, DataGridViewCellPaintingEventArgs e, int level)
{
// 根节点退出递归调用
if (level == 0)
{
return;
}
RectangleF uhRectangle;
int uhWidth;
using (
SolidBrush gridBrush = new SolidBrush(this.GridColor),
backColorBrush = new SolidBrush(e.CellStyle.BackColor))
{
using (Pen gridLinePen = new Pen(gridBrush))
{
StringFormat textFormat = new StringFormat();
textFormat.Alignment = StringAlignment.Center;
uhWidth = GetUnitHeaderWidth(node);
if (node.Nodes.Count == 0)
{
uhRectangle = new RectangleF(e.CellBounds.Left, e.CellBounds.Top + node.Level * _cellHeight,
uhWidth - 1, _cellHeight * (_columnDeep - node.Level) - 1);
}
else
{
uhRectangle = new RectangleF(e.CellBounds.Left, e.CellBounds.Top + node.Level * _cellHeight,
uhWidth - 1, _cellHeight - 1);
}
// 画矩形
e.Graphics.FillRectangle(backColorBrush, uhRectangle);
// 画底线
e.Graphics.DrawLine(gridLinePen, uhRectangle.Left,
uhRectangle.Bottom, uhRectangle.Right, uhRectangle.Bottom);
// 画右端线
e.Graphics.DrawLine(gridLinePen, uhRectangle.Right,
uhRectangle.Top, uhRectangle.Right, uhRectangle.Bottom);
if (!string.IsNullOrEmpty(node.Text))
{
float tmpWidth = uhRectangle.Width / 2;
if (this.Parent != null)
{
if (uhRectangle.Width - this.HorizontalScrollingOffset > this.Parent.Width)
{
tmpWidth = (this.Parent.Width - uhRectangle.Left) / 2;
}
else
{
tmpWidth = uhRectangle.Width / 2;
}
}
e.Graphics.DrawString(node.Text, this.Font, new SolidBrush(e.CellStyle.ForeColor),
uhRectangle.Left + tmpWidth
- e.Graphics.MeasureString(node.Text, this.Font).Width / 2 - 1,
uhRectangle.Top + uhRectangle.Height / 2
- e.Graphics.MeasureString(node.Text, this.Font).Height / 2);
}
if (node.PrevNode == null)
{
if (node.Parent != null)
{
PaintUnitHeader(node.Parent, e, level - 1);
}
}
// 周兴 20141116 修改
else
{
if (node != null && node.Parent != null)
{
// 最后一个节点才去判断父节点是否已经重绘
if (node.Parent.LastNode.Name.Equals(node.Name))
{
string name = node.Parent.FirstNode.Name;
if (this.Columns.Contains(name) && !this.Columns[name].Visible)
{
PaintUnitHeader(node.Parent, e, level - 1);
}
}
}
}
}
}
}
#endregion
#region 私有方法
///
/// 设置列表的背景颜色
///
public void SetDataGridViewRowColor()
{
try
{
// 只有开启了合并行才行
if (IsOpenMergeCellFlag && !string.IsNullOrEmpty(MergeOnlyColumn))
{
List rowColor = new List();
rowColor.Add(Constant.OA_COLOR_WHITE);
rowColor.Add(Constant.OA_COLOR_GREY);
int id = 0;
int j = 0;
for (int i = 0; i < this.Rows.Count; i++)
{
if (!string.IsNullOrEmpty(this.Rows[i].Cells[MergeOnlyColumn].Value + ""))
{
if (i == 0)
{
id = Convert.ToInt32(this.Rows[i].Cells[MergeOnlyColumn].Value);
}
else
{
if (id != Convert.ToInt32(this.Rows[i].Cells[MergeOnlyColumn].Value))
{
if (j == 0)
{
j = 1;
}
else
{
j = 0;
}
}
id = Convert.ToInt32(this.Rows[i].Cells[MergeOnlyColumn].Value);
}
this.Rows[i].DefaultCellStyle.BackColor = ColorTranslator.FromHtml(rowColor[j]);
this.Rows[i].Cells[MergeOnlyColumn].Tag = rowColor[j];
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
private DataTable BindData(DataTable dataTable, DataTable tmpTable, ArrayList dynamicnames)
{
for (int i = 0; i < dataTable.Rows.Count; i++)
{
DataRow row = null;
if (tmpTable.Rows.Count > 0)
{
for (int j = 0; j < tmpTable.Rows.Count; j++)
{
bool isNewRow = true;
for (int t = 0; t < dataTable.Columns.Count; t++)
{
if (tmpTable.Columns.Contains(dataTable.Columns[t].ColumnName))
{
if (tmpTable.Rows[j][dataTable.Columns[t].ColumnName]
== dataTable.Rows[i][dataTable.Columns[t].ColumnName])
{
isNewRow = false;
}
else
{
isNewRow = true;
break;
}
}
}
if (!isNewRow)
{
row = tmpTable.Rows[j];
}
}
if (row == null)
{
row = tmpTable.NewRow();
SetDataToTable(row, i, dataTable, dynamicnames);
tmpTable.Rows.Add(row);
}
else
{
SetDataToTable(row, i, dataTable, dynamicnames);
}
}
else
{
row = tmpTable.NewRow();
SetDataToTable(row, i, dataTable, dynamicnames);
tmpTable.Rows.Add(row);
}
}
return tmpTable;
}
private void SetDataToTable(DataRow row, int i, DataTable dataTable, ArrayList dynamicnames)
{
for (int t = 0; t < dataTable.Columns.Count; t++)
{
if (this.Columns.Contains(dataTable.Columns[t].ColumnName))
{
row[dataTable.Columns[t].ColumnName] =
dataTable.Rows[i][dataTable.Columns[t].ColumnName];
}
else
{
if (!DynamicColumnName.Equals(dataTable.Columns[t].ColumnName))
{
for (int j = 0; j < dynamicnames.Count; j++)
{
if (dynamicnames[j].Equals(dataTable.Rows[i][DynamicColumnName]))
{
row[dataTable.Columns[t].ColumnName + (j + 1)]
= dataTable.Rows[i][dataTable.Columns[t].ColumnName];
}
}
}
}
}
}
private DataTable LoadColumnHeaderTree(ArrayList dynamicnames)
{
TreeView treeview = new TreeView();
DataGridViewColumnCollection tempColumns = this.Columns;
DataTable tmpTable = new DataTable();
for (int i = 0; i < tempColumns.Count; i++)
{
if (DynamicColumnName.Equals(tempColumns[i].Name))
{
int x = 0;
for (int j = 0; j < dynamicnames.Count; j++)
{
TreeNode rootNode = new TreeNode(dynamicnames[j] + "");
rootNode.Text = dynamicnames[j] + "";
rootNode.Name = tempColumns[j].Name;
treeview.Nodes.Add(rootNode);
for (int t = 0; t < ChildNodeColumnName.Length; t++)
{
x++;
DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn();
column.Name = ChildNodeColumnName[t] + (j + 1);
column.DataPropertyName = ChildNodeColumnName[t] + (j + 1);
column.HeaderText = ChildNodeColumnText[t];
this.Columns.Insert(i + x, column);
tmpTable.Columns.Add(new DataColumn(column.Name));
TreeNode node = new TreeNode(ChildNodeColumnName[t]);
node.Text = ChildNodeColumnText[t];
node.Name = ChildNodeColumnName[t];
rootNode.Nodes.Add(node);
}
}
this.Columns.Remove(DynamicColumnName);
}
else
{
if (!tmpTable.Columns.Contains(tempColumns[i].Name))
{
tmpTable.Columns.Add(new DataColumn(tempColumns[i].Name));
TreeNode rootNode = new TreeNode(tempColumns[i].Name);
rootNode.Text = this.Columns[i].HeaderText;
rootNode.Name = tempColumns[i].Name;
treeview.Nodes.Add(rootNode);
}
}
}
this.ColumnTreeView = new TreeView[] { treeview };
return tmpTable;
}
///
/// 获得合并标题字段的宽度
///
///
///
private int GetUnitHeaderWidth(TreeNode node)
{
int uhWidth = 0;
if (node.Nodes == null || node.Nodes.Count == 0)
{
return this.Columns[GetColumnListNodeIndex(node)].Width;
}
for (int i = 0; i <= node.Nodes.Count - 1; i++)
{
//if (this.Columns[node.Nodes[i].Name].Visible)
//{
uhWidth = uhWidth + GetUnitHeaderWidth(node.Nodes[i]);
//}
}
return uhWidth;
}
///
/// 获得底层字段索引
///
///
///
private int GetColumnListNodeIndex(TreeNode node)
{
for (int i = 0; i <= _columnList.Count - 1; i++)
{
if (((TreeNode)_columnList[i]).Equals(node))
{
return i;
}
}
return -1;
}
private void GetColumnNodes(ArrayList alList, TreeNode node, bool isChecked)
{
if (!isChecked)
{
if (node.FirstNode == null)
{
alList.Add(node);
if (node.NextNode != null)
{
GetColumnNodes(alList, node.NextNode, false);
return;
}
if (node.Parent != null)
{
GetColumnNodes(alList, node.Parent, true);
return;
}
}
else
{
if (node.FirstNode != null)
{
GetColumnNodes(alList, node.FirstNode, false);
return;
}
}
}
else
{
if (node.FirstNode == null)
{
return;
}
if (node.NextNode != null)
{
GetColumnNodes(alList, node.NextNode, false);
return;
}
if (node.Parent != null)
{
GetColumnNodes(alList, node.Parent, true);
return;
}
}
}
///
/// 画单元格(合并单元格 周兴 2015-12-6 增加)
///
///
private void DrawCell(DataGridViewCellPaintingEventArgs e)
{
// 只有开启的才允许
if (!this.IsOpenMergeCellFlag || this.MergeColumnNames == null || this.MergeColumnNames.Count == 0
|| string.IsNullOrEmpty(MergeOnlyColumn) || !this.Columns.Contains(MergeOnlyColumn) || this.CurrentRow == null)
{
return;
}
if (e.CellStyle.Alignment == DataGridViewContentAlignment.NotSet)
{
e.CellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
}
Brush gridBrush = new SolidBrush(this.GridColor);
SolidBrush backBrush = new SolidBrush(e.CellStyle.BackColor);
SolidBrush fontBrush = new SolidBrush(e.CellStyle.ForeColor);
int cellwidth;
//上面相同的行数
int upRows = 0;
//下面相同的行数
int downRows = 0;
//总行数
int count = 0;
bool deilFlag = false;
bool isSeleted = false;
int upHeight = 0;
int downHeight = 0;
bool dDetailFlag = false;
if (MergeDetailColumnNames != null && MergeDetailColumnNames.Count > 0 && !string.IsNullOrEmpty(MergeDetailOnlyColumn))
{
deilFlag = true;
}
if (MergeDDetailColumnNames != null && MergeDDetailColumnNames.Count > 0 && !string.IsNullOrEmpty(MergeDDetailOnlyColumn))
{
dDetailFlag = true;
}
if (this.MergeColumnNames.Contains(this.Columns[e.ColumnIndex].Name) && e.RowIndex != -1)
{
cellwidth = e.CellBounds.Width;
Pen gridLinePen = new Pen(gridBrush);
string curValue = e.Value == null ? "" : e.Value.ToString().Trim();
string mergeOnlyColumnName = this.Rows[e.RowIndex].Cells[MergeOnlyColumn].Value + "";
string mergeDetailOnlyColumnName = string.Empty;
if (!string.IsNullOrEmpty(MergeDetailOnlyColumn))
{
mergeDetailOnlyColumnName = this.Rows[e.RowIndex].Cells[MergeDetailOnlyColumn].Value + "";
}
string mergeDDetailOnlyColumnName = string.Empty;
if (!string.IsNullOrEmpty(MergeDDetailOnlyColumn))
{
mergeDDetailOnlyColumnName = this.Rows[e.RowIndex].Cells[MergeDDetailOnlyColumn].Value + "";
}
string curSelected = this.CurrentRow.Cells[e.ColumnIndex].Value == null ? "" : this.CurrentRow.Cells[e.ColumnIndex].Value.ToString().Trim();
//if (!string.IsNullOrEmpty(curValue))
//{
#region 获取下面的行数
for (int i = e.RowIndex; i < this.Rows.Count; i++)
{
if ((this.Rows[i].Cells[e.ColumnIndex].Value + "").Equals(curValue) && mergeOnlyColumnName.Equals(this.Rows[i].Cells[MergeOnlyColumn].Value + ""))
{
if (dDetailFlag && MergeDDetailColumnNames.Contains(this.Columns[e.ColumnIndex].Name))
{
if (mergeDDetailOnlyColumnName.Equals(this.Rows[i].Cells[MergeDDetailOnlyColumn].Value + ""))
{
downRows++;
isSeleted = isSeleted || this.Rows[i].Selected;
downHeight += this.Rows[i].Height;
if (e.RowIndex != i)
{
cellwidth = cellwidth < this.Rows[i].Cells[e.ColumnIndex].Size.Width ? cellwidth : this.Rows[i].Cells[e.ColumnIndex].Size.Width;
}
}
else
{
break;
}
}
else if (deilFlag && MergeDetailColumnNames.Contains(this.Columns[e.ColumnIndex].Name))
{
if (mergeDetailOnlyColumnName.Equals(this.Rows[i].Cells[MergeDetailOnlyColumn].Value + ""))
{
downRows++;
isSeleted = isSeleted || this.Rows[i].Selected;
downHeight += this.Rows[i].Height;
if (e.RowIndex != i)
{
cellwidth = cellwidth < this.Rows[i].Cells[e.ColumnIndex].Size.Width ? cellwidth : this.Rows[i].Cells[e.ColumnIndex].Size.Width;
}
}
else
{
break;
}
}
//this.Rows[i].Cells[e.ColumnIndex].Selected = this.Rows[e.RowIndex].Cells[e.ColumnIndex].Selected;
else
{
downRows++;
isSeleted = isSeleted || this.Rows[i].Selected;
downHeight += this.Rows[i].Height;
if (e.RowIndex != i)
{
cellwidth = cellwidth < this.Rows[i].Cells[e.ColumnIndex].Size.Width ? cellwidth : this.Rows[i].Cells[e.ColumnIndex].Size.Width;
}
}
}
else
{
break;
}
}
#endregion
#region 获取上面的行数
for (int i = e.RowIndex; i >= 0; i--)
{
if ((this.Rows[i].Cells[e.ColumnIndex].Value + "").Equals(curValue) && mergeOnlyColumnName.Equals(this.Rows[i].Cells[MergeOnlyColumn].Value + ""))
{
if (dDetailFlag && MergeDDetailColumnNames.Contains(this.Columns[e.ColumnIndex].Name))
{
if (mergeDDetailOnlyColumnName.Equals(this.Rows[i].Cells[MergeDDetailOnlyColumn].Value + ""))
{
upRows++;
isSeleted = isSeleted || this.Rows[i].Selected;
upHeight += this.Rows[i].Height;
if (e.RowIndex != i)
{
cellwidth = cellwidth < this.Rows[i].Cells[e.ColumnIndex].Size.Width ? cellwidth : this.Rows[i].Cells[e.ColumnIndex].Size.Width;
}
}
else
{
break;
}
}
else if (deilFlag && MergeDetailColumnNames.Contains(this.Columns[e.ColumnIndex].Name))
{
if (mergeDetailOnlyColumnName.Equals(this.Rows[i].Cells[MergeDetailOnlyColumn].Value + ""))
{
upRows++;
isSeleted = isSeleted || this.Rows[i].Selected;
upHeight += this.Rows[i].Height;
if (e.RowIndex != i)
{
cellwidth = cellwidth < this.Rows[i].Cells[e.ColumnIndex].Size.Width ? cellwidth : this.Rows[i].Cells[e.ColumnIndex].Size.Width;
}
}
else
{
break;
}
}
else
{
//this.Rows[i].Cells[e.ColumnIndex].Selected = this.Rows[e.RowIndex].Cells[e.ColumnIndex].Selected;
upRows++;
isSeleted = isSeleted || this.Rows[i].Selected;
upHeight += this.Rows[i].Height;
if (e.RowIndex != i)
{
cellwidth = cellwidth < this.Rows[i].Cells[e.ColumnIndex].Size.Width ? cellwidth : this.Rows[i].Cells[e.ColumnIndex].Size.Width;
}
}
}
else
{
break;
}
}
#endregion
count = downRows + upRows - 1;
if (count < 2)
{
return;
}
//}
if (this.Rows[e.RowIndex].Selected || isSeleted)
{
backBrush.Color = e.CellStyle.SelectionBackColor;
fontBrush.Color = e.CellStyle.SelectionForeColor;
}
//以背景色填充
e.Graphics.FillRectangle(backBrush, e.CellBounds);
//画字符串
//PaintingFont(e, cellwidth, upRows, downRows, count);
string text = e.FormattedValue + "";
if (!string.IsNullOrEmpty(text))
{
DataGridViewCellStyle cellStyle = e.CellStyle;
TextFormatFlags textFormatFlags = this.ComputeTextFormatFlagsForCellStyleAlignment((this.RightToLeft == RightToLeft.Yes), cellStyle.Alignment, cellStyle.WrapMode);
if ((textFormatFlags & TextFormatFlags.SingleLine) != TextFormatFlags.Default)
{
textFormatFlags |= TextFormatFlags.EndEllipsis;
}
Rectangle rectangle2 = new Rectangle(e.CellBounds.X, e.CellBounds.Bottom - upHeight, cellwidth, upHeight + downHeight - e.CellBounds.Height);
int num = (cellStyle.WrapMode == DataGridViewTriState.True) ? 1 : 2;
rectangle2.Offset(0, num);
rectangle2.Width = rectangle2.Width;
rectangle2.Height -= num + 1;
if (rectangle2.Width > 0 && rectangle2.Height > 0 && rectangle2.Y >= 0 && rectangle2.X >=0)
{
TextRenderer.DrawText(e.Graphics, text, cellStyle.Font, rectangle2, fontBrush.Color, textFormatFlags);
}
}
if (downRows == 1)
{
e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left, e.CellBounds.Bottom - 1, e.CellBounds.Right - 1, e.CellBounds.Bottom - 1);
count = 0;
}
// 画右边线
e.Graphics.DrawLine(gridLinePen, e.CellBounds.Right - 1, e.CellBounds.Top, e.CellBounds.Right - 1, e.CellBounds.Bottom);
e.Handled = true;
}
}
private TextFormatFlags ComputeTextFormatFlagsForCellStyleAlignment(bool rightToLeft, DataGridViewContentAlignment alignment, DataGridViewTriState wrapMode)
{
TextFormatFlags textFormatFlags;
if (alignment <= DataGridViewContentAlignment.MiddleCenter)
{
switch (alignment)
{
case DataGridViewContentAlignment.TopLeft:
textFormatFlags = TextFormatFlags.Default;
if (rightToLeft)
{
textFormatFlags |= TextFormatFlags.Right;
goto IL_C0;
}
goto IL_C0;
case DataGridViewContentAlignment.TopCenter:
textFormatFlags = TextFormatFlags.HorizontalCenter;
goto IL_C0;
case (DataGridViewContentAlignment)3:
break;
case DataGridViewContentAlignment.TopRight:
textFormatFlags = TextFormatFlags.Default;
if (rightToLeft)
{
goto IL_C0;
}
textFormatFlags |= TextFormatFlags.Right;
goto IL_C0;
default:
if (alignment != DataGridViewContentAlignment.MiddleLeft)
{
if (alignment == DataGridViewContentAlignment.MiddleCenter)
{
textFormatFlags = (TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);
goto IL_C0;
}
}
else
{
textFormatFlags = TextFormatFlags.VerticalCenter;
if (rightToLeft)
{
textFormatFlags |= TextFormatFlags.Right;
goto IL_C0;
}
goto IL_C0;
}
break;
}
}
else
{
if (alignment <= DataGridViewContentAlignment.BottomLeft)
{
if (alignment != DataGridViewContentAlignment.MiddleRight)
{
if (alignment == DataGridViewContentAlignment.BottomLeft)
{
textFormatFlags = TextFormatFlags.Bottom;
if (rightToLeft)
{
textFormatFlags |= TextFormatFlags.Right;
goto IL_C0;
}
goto IL_C0;
}
}
else
{
textFormatFlags = TextFormatFlags.VerticalCenter;
if (rightToLeft)
{
goto IL_C0;
}
textFormatFlags |= TextFormatFlags.Right;
goto IL_C0;
}
}
else
{
if (alignment == DataGridViewContentAlignment.BottomCenter)
{
textFormatFlags = (TextFormatFlags.Bottom | TextFormatFlags.HorizontalCenter);
goto IL_C0;
}
if (alignment == DataGridViewContentAlignment.BottomRight)
{
textFormatFlags = TextFormatFlags.Bottom;
if (rightToLeft)
{
goto IL_C0;
}
textFormatFlags |= TextFormatFlags.Right;
goto IL_C0;
}
}
}
textFormatFlags = (TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);
IL_C0:
if (wrapMode == DataGridViewTriState.False)
{
textFormatFlags |= TextFormatFlags.SingleLine;
}
else
{
textFormatFlags |= TextFormatFlags.WordBreak;
}
textFormatFlags |= TextFormatFlags.NoPrefix;
textFormatFlags |= TextFormatFlags.PreserveGraphicsClipping;
if (rightToLeft)
{
textFormatFlags |= TextFormatFlags.RightToLeft;
}
return textFormatFlags;
}
///
/// 画字符串(合并单元格 周兴 2015-12-6 增加)
///
///
///
///
///
///
private void PaintingFont(System.Windows.Forms.DataGridViewCellPaintingEventArgs e, int cellwidth, int UpRows, int DownRows, int count)
{
SolidBrush fontBrush = new SolidBrush(e.CellStyle.ForeColor);
int fontheight = (int)e.Graphics.MeasureString(e.Value.ToString(), e.CellStyle.Font).Height;
int fontwidth = (int)e.Graphics.MeasureString(e.Value.ToString(), e.CellStyle.Font).Width;
int cellheight = e.CellBounds.Height;
if (e.CellStyle.Alignment == DataGridViewContentAlignment.BottomCenter)
{
e.Graphics.DrawString(e.FormattedValue + "", e.CellStyle.Font, fontBrush, e.CellBounds.X + (cellwidth - fontwidth) / 2, e.CellBounds.Y + cellheight * DownRows - fontheight);
}
else if (e.CellStyle.Alignment == DataGridViewContentAlignment.BottomLeft)
{
e.Graphics.DrawString(e.FormattedValue + "", e.CellStyle.Font, fontBrush, e.CellBounds.X, e.CellBounds.Y + cellheight * DownRows - fontheight);
}
else if (e.CellStyle.Alignment == DataGridViewContentAlignment.BottomRight)
{
e.Graphics.DrawString(e.FormattedValue + "", e.CellStyle.Font, fontBrush, e.CellBounds.X + cellwidth - fontwidth, e.CellBounds.Y + cellheight * DownRows - fontheight);
}
else if (e.CellStyle.Alignment == DataGridViewContentAlignment.MiddleCenter)
{
e.Graphics.DrawString(e.FormattedValue + "", e.CellStyle.Font, fontBrush, e.CellBounds.X + (cellwidth - fontwidth) / 2, e.CellBounds.Y - cellheight * (UpRows - 1) + (cellheight * count - fontheight) / 2);
}
else if (e.CellStyle.Alignment == DataGridViewContentAlignment.MiddleLeft)
{
e.Graphics.DrawString(e.FormattedValue + "", e.CellStyle.Font, fontBrush, e.CellBounds.X, e.CellBounds.Y - cellheight * (UpRows - 1) + (cellheight * count - fontheight) / 2);
}
else if (e.CellStyle.Alignment == DataGridViewContentAlignment.MiddleRight)
{
e.Graphics.DrawString(e.FormattedValue + "", e.CellStyle.Font, fontBrush, e.CellBounds.X + cellwidth - fontwidth, e.CellBounds.Y - cellheight * (UpRows - 1) + (cellheight * count - fontheight) / 2);
}
else if (e.CellStyle.Alignment == DataGridViewContentAlignment.TopCenter)
{
e.Graphics.DrawString(e.FormattedValue + "", e.CellStyle.Font, fontBrush, e.CellBounds.X + (cellwidth - fontwidth) / 2, e.CellBounds.Y - cellheight * (UpRows - 1));
}
else if (e.CellStyle.Alignment == DataGridViewContentAlignment.TopLeft)
{
e.Graphics.DrawString(e.FormattedValue + "", e.CellStyle.Font, fontBrush, e.CellBounds.X, e.CellBounds.Y - cellheight * (UpRows - 1));
}
else if (e.CellStyle.Alignment == DataGridViewContentAlignment.TopRight)
{
e.Graphics.DrawString(e.FormattedValue + "", e.CellStyle.Font, fontBrush, e.CellBounds.X + cellwidth - fontwidth, e.CellBounds.Y - cellheight * (UpRows - 1));
}
else
{
e.Graphics.DrawString(e.FormattedValue + "", e.CellStyle.Font, fontBrush, e.CellBounds.X + (cellwidth - fontwidth) / 2, e.CellBounds.Y - cellheight * (UpRows - 1) + (cellheight * count - fontheight) / 2);
}
}
#endregion
#region 受保护的方法/函数
protected override void OnColumnDisplayIndexChanged(DataGridViewColumnEventArgs e)
{
try
{
if (_isOpenTotalRow && !IsClickF12)
{
_columnInfos = this.GetDataGridViewColumnInfos();
if (_columnInfos != null)
{
for (int i = 0; i < _columnInfos.Length; i++)
{
if (_columnInfos[i].Visible)
{
NewText(_columnInfos[i].DataPropertyName, i);
}
}
CountTotalRow();
}
base.OnColumnDisplayIndexChanged(e);
}
}
catch (Exception ex)
{
throw ex;
}
}
protected override bool ProcessDialogKey(Keys keyData)
{
if (keyData == Keys.Enter)
{
return this.ProcessRightKey(keyData);
}
return base.ProcessDialogKey(keyData);
}
public new bool ProcessRightKey(Keys keyData)
{
if (keyData == Keys.Enter)
{
if (!IsProcessRightFlag || this.CurrentCell == null)
{
return false;
}
int rowIndex = this.CurrentCell.RowIndex;
int columnIndex = this.CurrentCell.ColumnIndex;
string columnName = this.Columns[columnIndex].Name;
// 选择商品时控制鼠标的行为
if ((columnName.Contains("Code") || columnName.Contains("OnlyCode"))
&& !string.IsNullOrEmpty(this.CurrentRow.Cells[columnName].EditedFormattedValue + "")
&& !this.CurrentRow.Cells[columnName].EditedFormattedValue.ToString()
.Equals(this.CurrentRow.Cells[columnName].Value))
{
base.ProcessRightKey(keyData);
}
// 如果是数值类型,数值合法时才跳到下一个可输入单元格
if (this.CurrentCell != null && this.CurrentCell.ValueType != null
&& this.CurrentCell.ValueType.IsValueType
&& this.CurrentCell.EditType != null
&& "DataGridViewTextBoxEditingControl".Equals(this.CurrentCell.EditType.Name))
{
decimal temp = -1;
bool flag = decimal.TryParse(this.CurrentRow.Cells[columnName].EditedFormattedValue + "", out temp);
// 说明有非数字
if (!flag)
{
return true;
}
}
DataGridViewColumnInfo[] columnInfo = this.GetDataGridViewColumnInfos();
if (columnInfo != null && columnInfo.Length > 0)
{
for (int i = rowIndex; i < this.Rows.Count; i++)
{
bool flag = false;
for (int j = 0; j < columnInfo.Length; j++)
{
if (i == rowIndex)
{
if (!flag && !columnName.Equals(columnInfo[j].ColumnName))
{
continue;
}
else
{
if (!flag)
{
j += 1;
}
flag = true;
}
}
if (columnInfo.Length > j && !this.Rows[i].Cells[columnInfo[j].ColumnName].ReadOnly
&& this.Rows[i].Cells[columnInfo[j].ColumnName].Visible)
{
//this.CurrentCell = this.Rows[i].Cells[columnInfo[j].ColumnName];
this.Rows[i].Cells[columnInfo[j].ColumnName].Selected = true;
return true;
}
}
}
}
//base.ProcessRightKey(keyData);
// 如果datagridview只读,按回车就会跳到下一行
//if (!isEnterKey && this.ReadOnly)
//{
// if (this.CurrentCell.RowIndex < this.Rows.Count - 1)
// {
// this.CurrentCell = this.Rows[this.CurrentCell.RowIndex + 1].Cells[0];
// }
//}
}
return true;
}
protected override bool ProcessDataGridViewKey(KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
//isEnterKey = true;
return this.ProcessRightKey(e.KeyData);
}
return base.ProcessDataGridViewKey(e);
}
protected override void OnCellEnter(DataGridViewCellEventArgs e)
{
base.OnCellEnter(e);
}
protected override void OnMouseUp(MouseEventArgs e)
{
// used to keep extra mouse moves from selecting more rows when collapsing
base.OnMouseUp(e);
this._inExpandCollapseMouseCapture = false;
}
protected override void OnMouseMove(MouseEventArgs e)
{
// while we are expanding and collapsing a node mouse moves are
// supressed to keep selections from being messed up.
if (!this._inExpandCollapseMouseCapture)
base.OnMouseMove(e);
}
protected virtual void SetBackColorCell(int viewRowIndex, int viewColumnIndex)
{
if (!this.Visible)
{
return;
}
if (CellBackColorFlag == CellBackColorFlags.None)
{
return;
}
if (viewRowIndex < 0)
{
for (int i = 0; i < this.Rows.Count; i++)
{
SetBackColorCell(i, viewColumnIndex);
}
}
else if (viewColumnIndex < 0)
{
for (int i = 0; i < this.Columns.Count; i++)
{
SetBackColorCell(viewRowIndex, i);
}
}
else if (0 <= viewRowIndex && 0 <= viewColumnIndex)
{
DataGridViewCell cell = this.Rows[viewRowIndex].Cells[viewColumnIndex];
if (cell == null)
{
return;
}
if (this.ReadOnly || this.Rows[viewRowIndex].ReadOnly ||
this.Columns[viewColumnIndex].ReadOnly ||
this.Rows[viewRowIndex].Cells[viewColumnIndex].ReadOnly)
{
if (this.CellBackColorReadOnly != Color.Transparent &&
(this.CellBackColorFlag &
CellBackColorFlags.ReadOnlyBackColor) != 0)
{
cell.Style.BackColor = this.CellBackColorReadOnly;
return;
}
}
if (CurrentDataTable != null)
{
if ((CellBackColorFlag & CellBackColorFlags.ChangesBackColor) != 0)
{
DataRowView dataRowView = this.GetDataRowView(viewRowIndex);
if (dataRowView != null)
{
switch (dataRowView.Row.RowState)
{
case DataRowState.Added:
cell.Style.BackColor = CellBackColorAdded;
return;
case DataRowState.Modified:
string dataPropertyName =
this.Columns[viewColumnIndex].DataPropertyName;
if (string.IsNullOrEmpty(dataPropertyName))
{
break;
}
object valueOriginal =
dataRowView.Row[dataPropertyName, DataRowVersion.Original];
object valueCurrent =
dataRowView.Row[dataPropertyName, DataRowVersion.Current];
if (!valueOriginal.Equals(valueCurrent))
{
if (valueOriginal.Equals(DBNull.Value) &&
valueCurrent.Equals(string.Empty) ||
valueCurrent.Equals(DBNull.Value) &&
valueOriginal.Equals(string.Empty))
{
break;
}
cell.Style.BackColor = CellBackColorModified;
return;
}
break;
case DataRowState.Deleted:
cell.Style.BackColor = CellBackColorDeleted;
return;
default:
break;
}
}
}
}
if (this.CellBackColorNochanged != Color.Transparent &&
(cell.Style.BackColor != this.CellBackColorNochanged))
{
cell.Style.BackColor = this.CellBackColorNochanged;
}
}
}
protected void DispRowCount()
{
if (IsDispRowCount)
{
Graphics graphics = this.CreateGraphics();
OnPaint(new PaintEventArgs(graphics, new Rectangle(new Point(0, 0),
this.TopLeftHeaderCell.Size)));
graphics.Dispose();
}
}
protected void OnCsvCoverting(CsvConvertingEventArgs e)
{
if (CsvConverting != null)
{
CsvConverting(this, e);
}
}
#region 树形结构
public event ExpandingEventHandler NodeExpanding;
public event ExpandedEventHandler NodeExpanded;
public event CollapsingEventHandler NodeCollapsing;
public event CollapsedEventHandler NodeCollapsed;
protected virtual void OnNodeExpanding(ExpandingEventArgs e)
{
if (this.NodeExpanding != null)
{
NodeExpanding(this, e);
}
}
protected virtual void OnNodeExpanded(ExpandedEventArgs e)
{
if (this.NodeExpanded != null)
{
NodeExpanded(this, e);
}
}
protected virtual void OnNodeCollapsing(CollapsingEventArgs e)
{
if (this.NodeCollapsing != null)
{
NodeCollapsing(this, e);
}
}
protected virtual void OnNodeCollapsed(CollapsedEventArgs e)
{
if (this.NodeCollapsed != null)
{
NodeCollapsed(this, e);
}
}
#endregion
#endregion
#region 重写方法
protected override bool SetCurrentCellAddressCore(int columnIndex, int rowIndex, bool setAnchorCellAddress, bool validateCurrentCell, bool throughMouseClick)
{
try
{
return base.SetCurrentCellAddressCore(columnIndex, rowIndex, setAnchorCellAddress, validateCurrentCell, throughMouseClick);
}
catch (Exception ex)
{
return false;
}
}
private bool _isFlag = false;
protected override void OnCellValueChanged(DataGridViewCellEventArgs e)
{
if (e.ColumnIndex >= 0 && e.RowIndex >= 0 && !_isFlag)
{
string value = this.Rows[e.RowIndex].Cells[e.ColumnIndex].EditedFormattedValue + "";
if (!string.IsNullOrEmpty(value))
{
decimal valueDec = 0;
string format = this.Columns[e.ColumnIndex].DefaultCellStyle.Format;
bool flag = decimal.TryParse(value + "", out valueDec);
if (flag && format.IndexOf("F") >= 0)
{
_isFlag = true;
this.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = valueDec.ToString(format);
_isFlag = false;
}
}
}
base.OnCellValueChanged(e);
}
protected override void OnSelectionChanged(EventArgs e)
{
try
{
base.OnSelectionChanged(e);
// 开合并行之后,在切换行处理
if (IsOpenMergeCellFlag && !string.IsNullOrEmpty(MergeOnlyColumn) &&
MergeColumnNames != null && MergeColumnNames.Count > 0 &&
this.Columns.Contains(MergeOnlyColumn) && this.CurrentCell != null
&& (string.IsNullOrEmpty(this.Tag + "") || Convert.ToBoolean(this.Tag)))
{
Color color;
// 先清空颜色
for (int i = 0; i < this.Rows.Count; i++)
{
if (string.IsNullOrEmpty(this.Rows[i].Cells[MergeOnlyColumn].Tag + ""))
{
color = Color.White;
}
else
{
color = ColorTranslator.FromHtml(this.Rows[i].Cells[MergeOnlyColumn].Tag + "");
}
for (int j = 0; j < this.Columns.Count; j++)
{
if (this.Rows[i].Cells[j].Style.BackColor == ColorTranslator.FromHtml(Constant.COLOR_RED))
{
this.Rows[i].Cells[j].Style.BackColor = color;
this.Rows[i].Cells[j].Style.ForeColor = Color.Black;
}
}
}
// 向上找 ,如果有,就把背景颜色修改为选中
string onlyColumnC = this.Rows[this.CurrentCell.RowIndex].Cells[MergeOnlyColumn].Value + "";
string onlyDetailColumnC = string.Empty;
if (!string.IsNullOrEmpty(MergeDetailOnlyColumn))
{
onlyDetailColumnC = this.Rows[this.CurrentCell.RowIndex].Cells[MergeDetailOnlyColumn].Value + "";
}
string onlyDDetailColumnC = string.Empty;
if (!string.IsNullOrEmpty(MergeDDetailOnlyColumn))
{
onlyDDetailColumnC = this.Rows[this.CurrentCell.RowIndex].Cells[MergeDDetailOnlyColumn].Value + "";
}
List tempColumns = new List();
if (MergeDDetailColumnNames != null && MergeDDetailColumnNames.Count > 0)
{
tempColumns.AddRange(MergeDDetailColumnNames.ToArray());
}
if (MergeDetailColumnNames != null && MergeDetailColumnNames.Count > 0)
{
tempColumns.AddRange(MergeDetailColumnNames.ToArray());
}
if (this.CurrentCell.RowIndex >= 1)
{
for (int i = this.CurrentCell.RowIndex - 1; i >= 0; i--)
{
if (!string.IsNullOrEmpty(onlyDDetailColumnC) && onlyDDetailColumnC.Equals(this.Rows[i].Cells[MergeDDetailOnlyColumn].Value + ""))
{
if (MergeDDetailColumnNames != null)
{
for (int j = 0; j < MergeDDetailColumnNames.Count; j++)
{
if (this.Columns.Contains(MergeDDetailColumnNames[j]))
{
this.Rows[i].Cells[MergeDDetailColumnNames[j]].Style.BackColor = ColorTranslator.FromHtml(Constant.COLOR_RED);
this.Rows[i].Cells[MergeDDetailColumnNames[j]].Style.ForeColor = Color.White;
}
}
}
}
else if (!string.IsNullOrEmpty(onlyDetailColumnC) && onlyDetailColumnC.Equals(this.Rows[i].Cells[MergeDetailOnlyColumn].Value + ""))
{
if (MergeDetailColumnNames != null)
{
for (int j = 0; j < MergeDetailColumnNames.Count; j++)
{
if (this.Columns.Contains(MergeDetailColumnNames[j]))
{
this.Rows[i].Cells[MergeDetailColumnNames[j]].Style.BackColor = ColorTranslator.FromHtml(Constant.COLOR_RED);
this.Rows[i].Cells[MergeDetailColumnNames[j]].Style.ForeColor = Color.White;
}
}
}
}
else if (!string.IsNullOrEmpty(onlyColumnC) && onlyColumnC.Equals(this.Rows[i].Cells[MergeOnlyColumn].Value + ""))
{
for (int j = 0; j < MergeColumnNames.Count; j++)
{
if (this.Columns.Contains(MergeColumnNames[j]) && !tempColumns.Contains(MergeColumnNames[j]))
{
this.Rows[i].Cells[MergeColumnNames[j]].Style.BackColor = ColorTranslator.FromHtml(Constant.COLOR_RED);
this.Rows[i].Cells[MergeColumnNames[j]].Style.ForeColor = Color.White;
}
}
}
}
}
// 向下 ,如果有,就把背景颜色修改为选中
if (this.CurrentCell.RowIndex <= this.Rows.Count - 2)
{
for (int i = this.CurrentCell.RowIndex + 1; i <= this.Rows.Count - 1; i++)
{
if (!string.IsNullOrEmpty(onlyDDetailColumnC) && onlyDDetailColumnC.Equals(this.Rows[i].Cells[MergeDDetailOnlyColumn].Value + ""))
{
if (MergeDDetailColumnNames != null)
{
for (int j = 0; j < MergeDDetailColumnNames.Count; j++)
{
if (this.Columns.Contains(MergeDDetailColumnNames[j]))
{
this.Rows[i].Cells[MergeDDetailColumnNames[j]].Style.BackColor = ColorTranslator.FromHtml(Constant.COLOR_RED);
this.Rows[i].Cells[MergeDDetailColumnNames[j]].Style.ForeColor = Color.White;
}
}
}
}
else if (!string.IsNullOrEmpty(onlyDetailColumnC) && onlyDetailColumnC.Equals(this.Rows[i].Cells[MergeDetailOnlyColumn].Value + ""))
{
if (MergeDetailColumnNames != null)
{
for (int j = 0; j < MergeDetailColumnNames.Count; j++)
{
if (this.Columns.Contains(MergeDetailColumnNames[j]))
{
this.Rows[i].Cells[MergeDetailColumnNames[j]].Style.BackColor = ColorTranslator.FromHtml(Constant.COLOR_RED);
this.Rows[i].Cells[MergeDetailColumnNames[j]].Style.ForeColor = Color.White;
}
}
}
}
else if (!string.IsNullOrEmpty(onlyColumnC) && onlyColumnC.Equals(this.Rows[i].Cells[MergeOnlyColumn].Value + ""))
{
for (int j = 0; j < MergeColumnNames.Count; j++)
{
if (this.Columns.Contains(MergeColumnNames[j]) && !tempColumns.Contains(MergeColumnNames[j]))
{
this.Rows[i].Cells[MergeColumnNames[j]].Style.BackColor = ColorTranslator.FromHtml(Constant.COLOR_RED);
this.Rows[i].Cells[MergeColumnNames[j]].Style.ForeColor = Color.White;
}
}
}
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
protected override void OnHandleCreated(EventArgs e)
{
base.OnHandleCreated(e);
// this control is used to temporarly hide the vertical scroll bar
hideScrollBarControl = new Control();
hideScrollBarControl.Visible = false;
hideScrollBarControl.Enabled = false;
hideScrollBarControl.TabStop = false;
// control is disposed automatically when the grid is disposed
this.Controls.Add(hideScrollBarControl);
}
protected override void OnRowEnter(DataGridViewCellEventArgs e)
{
// ensure full row select
base.OnRowEnter(e);
if (this.SelectionMode == DataGridViewSelectionMode.CellSelect ||
(this.SelectionMode == DataGridViewSelectionMode.FullRowSelect &&
base.Rows[e.RowIndex].Selected == false))
{
this.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
base.Rows[e.RowIndex].Selected = true;
}
}
private void LockVerticalScrollBarUpdate(bool lockUpdate/*, bool delayed*/)
{
// Temporarly hide/show the vertical scroll bar by changing its parent
if (!this._inExpandCollapse)
{
if (lockUpdate)
{
this.VerticalScrollBar.Parent = hideScrollBarControl;
}
else
{
this.VerticalScrollBar.Parent = this;
}
}
}
protected override void OnPaint(PaintEventArgs e)
{
try
{
try
{
base.OnPaint(e);
}
catch (Exception ex)
{
ex.ToString();
}
// 头部分的重绘
if (this.HitTest(e.ClipRectangle.Left + 1, e.ClipRectangle.Top + 1).Type == DataGridViewHitTestType.TopLeftHeader)
{
// 属性设置需要显示总行数
if (IsDispRowCount)
{
// 当前选择行的Index
int currentIndex = 0;
if (this.CurrentRow == null)
{
return;
}
else
{
currentIndex = this.CurrentRow.Index;
}
// 内容的绘制
Rectangle rect = new Rectangle(0, 0, this.RowHeadersWidth - 4, this.ColumnHeadersHeight);
int rowCount = this.RowCount;
if (this.AllowUserToAddRows)
{
rowCount--;
}
string comment = string.Format("{0}/{1}",
currentIndex + 1,
rowCount
);
TextRenderer.DrawText(
e.Graphics,
comment, this.ColumnHeadersDefaultCellStyle.Font,
rect, this.ColumnHeadersDefaultCellStyle.ForeColor,
TextFormatFlags.VerticalCenter | TextFormatFlags.Right
);
}
}
}
catch (Exception ex)
{
throw ex;
//Debug.Assert(false, "Error", ex.Message);
}
}
///
/// 滚动
///
///
protected override void OnScroll(ScrollEventArgs e)
{
try
{
bool scrollDirection = (e.ScrollOrientation == ScrollOrientation.HorizontalScroll);
base.OnScroll(e);
if (_isOpenTotalRow)
{
SetTxtTop();
SetTxtLeft();
}
if (RefreshAtHscroll && scrollDirection)
{
this.Refresh();
}
}
catch (Exception ex)
{
throw ex;
}
}
protected override void OnRowHeadersWidthChanged(EventArgs e)
{
if (_isOpenTotalRow && _columnInfos != null)
{
if (findTextBox("txt" + this.Name) == null)
{
return;
}
findTextBox("txt" + this.Name).Width = this.RowHeadersWidth;
for (int i = 0; i < _columnInfos.Length; i++)
{
if (_columnInfos[i].Visible && findTextBox("txt" + _columnInfos[i].DataPropertyName) != null)
{
findTextBox("txt" + _columnInfos[i].DataPropertyName).Left = getLeft(_columnInfos[i].DataPropertyName, i);
}
}
}
base.OnRowHeadersWidthChanged(e);
}
///
/// 列宽度改变时的重写
///
///
protected override void OnColumnWidthChanged(DataGridViewColumnEventArgs e)
{
if (_isOpenTotalRow && _columnInfos != null && !IsAutoResizeColumns)
{
_columnInfos = GetDataGridViewColumnInfos();
//bool flag = false;
//for (int i = 0; i < _columnInfos.Length; i++)
//{
// if (_columnInfos[i].DataPropertyName.Equals(e.Column.DataPropertyName))
// {
// if (findTextBox("txt" + _columnInfos[i].DataPropertyName) == null)
// {
// return;
// }
// findTextBox("txt" + _columnInfos[i].DataPropertyName).Width = e.Column.Width;
// flag = true;
// }
// if (flag && _columnInfos[i].Visible)
// {
// findTextBox("txt" + _columnInfos[i].DataPropertyName).Left = getLeft(_columnInfos[i].DataPropertyName, i);
// }
//}
for (int i = 0; i < _columnInfos.Length; i++)
{
if (_columnInfos[i].Visible)
{
NewText(_columnInfos[i].DataPropertyName, i);
}
}
CountTotalRow();
}
Graphics g = Graphics.FromHwnd(this.Handle);
float uwh = g.MeasureString(e.Column.HeaderText, this.Font).Width;
if (uwh >= e.Column.Width)
{
e.Column.Width = Convert.ToInt16(uwh);
}
base.OnColumnWidthChanged(e);
if (RefreshAtHscroll)
{
this.Refresh();
}
}
protected override void OnCellPainting(DataGridViewCellPaintingEventArgs e)
{
if (e.ColumnIndex < 0 || _columnDeep == 1)
{
// 周兴 2015-12-6 增加 合并单元格
if (e.RowIndex > -1 && e.ColumnIndex > -1)
{
DrawCell(e);
}
base.OnCellPainting(e);
return;
}
if (e.RowIndex == -1)
{
object[] colList = ColumnList.ToArray();
if (e.ColumnIndex >= colList.Length)
{
e.Handled = true;
return;
}
PaintUnitHeader((TreeNode)colList[e.ColumnIndex], e, _columnDeep);
e.Handled = true;
}
else
{
// 周兴 2015-12-6 增加 合并单元格
if (e.RowIndex > -1 && e.ColumnIndex > -1)
{
DrawCell(e);
}
base.OnCellPainting(e);
}
}
protected override void OnRowsAdded(DataGridViewRowsAddedEventArgs e)
{
if (_isOpenTotalRow && IsAutoCountSum)
{
CountTotalRow();
}
base.OnRowsAdded(e);
// Notify the row when it is added to the base grid
int count = e.RowCount - 1;
TreeGridNode row;
while (count >= 0)
{
row = base.Rows[e.RowIndex + count] as TreeGridNode;
if (row != null)
{
row.Sited();
}
count--;
}
}
internal protected void UnSiteAll()
{
this.UnSiteNode(this._root);
}
internal protected virtual void UnSiteNode(TreeGridNode node)
{
if (node != null && (node.IsSited || node.IsRoot))
{
// remove child rows first
foreach (TreeGridNode childNode in node.Nodes)
{
this.UnSiteNode(childNode);
}
// now remove this row except for the root
if (!node.IsRoot)
{
// zx 解决加载树形结构页面关闭时的bug
try
{
base.Rows.Remove(node);
// Row isn't sited in the grid anymore after remove. Note that we cannot
// Use the RowRemoved event since we cannot map from the row index to
// the index of the expandable row/node.
node.UnSited();
}
catch (Exception ex)
{
throw ex;
}
}
}
}
internal protected virtual bool CollapseNode(TreeGridNode node)
{
if (node.IsExpanded)
{
CollapsingEventArgs exp = new CollapsingEventArgs(node);
this.OnNodeCollapsing(exp);
if (!exp.Cancel)
{
this.LockVerticalScrollBarUpdate(true);
this.SuspendLayout();
_inExpandCollapse = true;
node.IsExpanded = false;
foreach (TreeGridNode childNode in node.Nodes)
{
Debug.Assert(childNode.RowIndex != -1, "Row is NOT in the grid.");
this.UnSiteNode(childNode);
}
CollapsedEventArgs exped = new CollapsedEventArgs(node);
this.OnNodeCollapsed(exped);
//TODO: Convert this to a specific NodeCell property
_inExpandCollapse = false;
this.LockVerticalScrollBarUpdate(false);
this.ResumeLayout(true);
this.InvalidateCell(node.Cells[0]);
}
return !exp.Cancel;
}
else
{
// row isn't expanded, so we didn't do anything.
return false;
}
}
internal protected virtual void SiteNode(TreeGridNode node)
{
//TODO: Raise exception if parent node is not the root or is not sited.
int rowIndex = -1;
TreeGridNode currentRow;
node._grid = this;
if (node.Parent != null && node.Parent.IsRoot == false)
{
// row is a child
Debug.Assert(node.Parent != null && node.Parent.IsExpanded == true);
if (node.Index > 0)
{
currentRow = node.Parent.Nodes[node.Index - 1];
}
else
{
currentRow = node.Parent;
}
}
else
{
// row is being added to the root
if (node.Index > 0)
{
currentRow = node.Parent.Nodes[node.Index - 1];
}
else
{
currentRow = null;
}
}
if (currentRow != null)
{
while (currentRow.Level >= node.Level)
{
if (currentRow.RowIndex < base.Rows.Count - 1)
{
currentRow = base.Rows[currentRow.RowIndex + 1] as TreeGridNode;
Debug.Assert(currentRow != null);
}
else
// no more rows, site this node at the end.
break;
}
if (currentRow == node.Parent)
rowIndex = currentRow.RowIndex + 1;
else if (currentRow.Level < node.Level)
rowIndex = currentRow.RowIndex;
else
rowIndex = currentRow.RowIndex + 1;
}
else
rowIndex = 0;
Debug.Assert(rowIndex != -1);
this.SiteNode(node, rowIndex);
Debug.Assert(node.IsSited);
node.IsExpanded = _isExpandAll;
if (node.IsExpanded)
{
// add all child rows to display
foreach (TreeGridNode childNode in node.Nodes)
{
//TODO: could use the more efficient SiteRow with index.
this.SiteNode(childNode);
}
}
}
private bool _isExpandAll = false;
///
/// 是否打开所有树形结构的节点
///
public bool IsExpandAll
{
set
{
if (HasNode && !string.IsNullOrEmpty(NodeColumnName))
{
_isExpandAll = value;
}
}
}
protected override void OnColumnAdded(DataGridViewColumnEventArgs e)
{
if (typeof(TreeGridColumn).IsAssignableFrom(e.Column.GetType()))
{
if (_expandableColumn == null)
{
// identify the expanding column.
_expandableColumn = (TreeGridColumn)e.Column;
}
else
{
// this.Columns.Remove(e.Column);
//throw new InvalidOperationException("Only one TreeGridColumn per TreeGridView is supported.");
}
}
// Expandable Grid doesn't support sorting. This is just a limitation of the sample.
//e.Column.SortMode = DataGridViewColumnSortMode.Automatic;
base.OnColumnAdded(e);
e.Column.HeaderCell.Style.WrapMode = DataGridViewTriState.False;
}
internal protected virtual void SiteNode(TreeGridNode node, int index)
{
if (index < base.Rows.Count)
{
base.Rows.Insert(index, node);
}
else
{
// for the last item.
base.Rows.Add(node);
}
}
internal protected virtual bool ExpandNode(TreeGridNode node)
{
if (!node.IsExpanded || this._virtualNodes)
{
ExpandingEventArgs exp = new ExpandingEventArgs(node);
this.OnNodeExpanding(exp);
if (!exp.Cancel)
{
this.LockVerticalScrollBarUpdate(true);
this.SuspendLayout();
_inExpandCollapse = true;
node.IsExpanded = true;
//TODO Convert this to a InsertRange
foreach (TreeGridNode childNode in node.Nodes)
{
Debug.Assert(childNode.RowIndex == -1, "Row is already in the grid.");
this.SiteNode(childNode);
//this.BaseRows.Insert(rowIndex + 1, childRow);
//TODO : remove -- just a test.
//childNode.Cells[0].Value = "child";
}
ExpandedEventArgs exped = new ExpandedEventArgs(node);
this.OnNodeExpanded(exped);
//TODO: Convert this to a specific NodeCell property
_inExpandCollapse = false;
this.LockVerticalScrollBarUpdate(false);
this.ResumeLayout(true);
this.InvalidateCell(node.Cells[0]);
}
return !exp.Cancel;
}
else
{
// row is already expanded, so we didn't do anything.
return false;
}
}
private void InitNode(DataTable dataTable, TreeGridNode node,
SortedList sortedlist, DataRow[] dataRows)
{
DataRow[] dataRowsTmp = null;
TreeGridNode nodeTmp = null;
for (int i = 0; i < dataRows.Length; i++)
{
nodeTmp = node.Nodes.Add(dataRows[i], dataTable.Columns, this.Columns, sortedlist, out sortedlist);
dataRowsTmp = dataTable.Select(" ParentID = " + dataRows[i][NodeColumnName]);
InitNode(dataTable, nodeTmp, sortedlist, dataRowsTmp);
}
}
#endregion
#region 事件
#region 单元格事件
private void dkDataGridView_CellEnter(object sender, DataGridViewCellEventArgs e)
{
if (this.IsHandleCreated)
{
DispRowCount();
}
}
private void dkDataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
// 清除错误显示
}
private void dkDataGridView_CellValidated(object sender, DataGridViewCellEventArgs e)
{
DataTable dtblDataTable = GetDataTable();
if (dtblDataTable != null && this.IsCurrentRowDirty)
{
DataGridView dataGridView = (DataGridView)sender;
DataColumn dataColumn =
dtblDataTable.Columns[dataGridView.Columns[e.ColumnIndex].DataPropertyName];
if (dataColumn != null)
{
if (!dataColumn.AllowDBNull)
{
if (dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value == DBNull.Value)
{
if (dataColumn.DataType.Equals(typeof(string)))
{
dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = string.Empty;
}
}
}
}
}
}
private bool IsSelectSameCell(int selectCellRowIndex, int selectCellColumnIndex)
{
if ((selectCellRowIndex == _selectCellRowCol[0]) && (selectCellColumnIndex == _selectCellRowCol[1]))
{
return true;
}
else
{
return false;
}
}
private void SetMnuFrozenText(int intRowIndex, int intColumnIndex)
{
bool isSelectSameCell = true;
isSelectSameCell = IsSelectSameCell(intRowIndex, intColumnIndex);
if (isSelectSameCell && _isFrozen)
{
_mnuFrozen.Text = ControlsTips.DK_DataGridView_UnFrozen;
}
else
{
_mnuFrozen.Text = ControlsTips.DK_DataGridView_Frozen;
}
}
private void SetGridViewColumnHeaderMenu()
{
_ctxColumnHeader.Items.Clear();
if (this.ContextMenuVisible != ContextMenuVisibleFlags.None)
{
AddToolStripSeparator(_ctxColumnHeader);
_ctxColumnHeader.Items.Add(this._mnuFrozen);
}
if ((this.ContextMenuVisible & ContextMenuVisibleFlags.Refine) ==
ContextMenuVisibleFlags.Refine)
{
AddToolStripSeparator(_ctxColumnHeader);
_ctxColumnHeader.Items.Add(this._mnuRefine);
_ctxColumnHeader.Items.Add(this._mnuUnfilter);
}
if (IsExportFlag && (this.ContextMenuVisible & ContextMenuVisibleFlags.FileOut) ==
ContextMenuVisibleFlags.FileOut)
{
AddToolStripSeparator(_ctxColumnHeader);
_ctxColumnHeader.Items.Add(this._mnuOutputFile);
_ctxColumnHeader.Items.Add(this._mnuOutputFileXls);
}
}
private void SetGridViewCellMenu(DataGridViewRow gridViewRow)
{
_ctxCell.Items.Clear();
// 右键菜单的Item设定
if (this.ContextMenuVisible != ContextMenuVisibleFlags.None)
{
AddToolStripSeparator(_ctxCell);
_ctxCell.Items.Add(this._mnuFrozen);
}
if (!gridViewRow.IsNewRow)
{
// 不存在新建行的情况
if ((this.ContextMenuVisible & ContextMenuVisibleFlags.Refine) ==
ContextMenuVisibleFlags.Refine)
{
AddToolStripSeparator(_ctxCell);
_ctxCell.Items.Add(this._mnuRefine);
_ctxCell.Items.Add(this._mnuFilter);
_ctxCell.Items.Add(this._mnuFilterExcept);
_ctxCell.Items.Add(this._mnuUnfilter);
}
}
else
{
// 新建行的情况
if ((this.ContextMenuVisible & ContextMenuVisibleFlags.Refine) ==
ContextMenuVisibleFlags.Refine)
{
AddToolStripSeparator(_ctxCell);
_ctxCell.Items.Add(this._mnuRefine);
_ctxCell.Items.Add(this._mnuUnfilter);
}
}
if (IsExportFlag && (this.ContextMenuVisible & ContextMenuVisibleFlags.FileOut) ==
ContextMenuVisibleFlags.FileOut)
{
AddToolStripSeparator(_ctxCell);
_ctxCell.Items.Add(this._mnuOutputFile);
_ctxCell.Items.Add(this._mnuOutputFileXls);
}
//if (IsPrintFlag && (this.ContextMenuVisible & ContextMenuVisibleFlags.Print) == ContextMenuVisibleFlags.Print)
//{
// AddToolStripSeparator(_ctxCell);
// _ctxCell.Items.Add(this._mnuPrint);
//}
}
private void DataGridViewMouseDownRight(DataGridView.HitTestInfo gridViewHitTestInfo, MouseEventArgs e)
{
try
{
// 如果是数值类型,数值合法时才跳到下一个可输入单元格
if (this.CurrentCell != null && this.CurrentCell.ValueType != null
&& this.CurrentCell.ValueType.IsValueType
&& this.CurrentCell.EditType != null
&& "DataGridViewTextBoxEditingControl".Equals(this.CurrentCell.EditType.Name))
{
if ("int".Equals(this.CurrentCell.ValueType.Name.ToLower())
|| "decimal".Equals(this.CurrentCell.ValueType.Name.ToLower())
|| "double".Equals(this.CurrentCell.ValueType.Name.ToLower()))
{
string columnName = this.Columns[this.CurrentCell.ColumnIndex].Name;
decimal temp = -1;
bool flag = decimal.TryParse(this.CurrentRow.Cells[columnName].EditedFormattedValue + "", out temp);
// 说明有非数字
if (!flag)
{
return;
}
}
}
if (gridViewHitTestInfo.Type == DataGridViewHitTestType.ColumnHeader)
{
// 点击列头的情况下,设定右键菜单的Item
SetGridViewColumnHeaderMenu();
Point point = new Point(e.X, e.Y);
point = this.PointToScreen(point);
_ctxColumnHeader.Tag = gridViewHitTestInfo;
_ctxColumnHeader.Show(point);
_gridRowIndex = 0;
_gridColumnindex = gridViewHitTestInfo.ColumnIndex;
}
else if (gridViewHitTestInfo.Type == DataGridViewHitTestType.Cell)
{
// 点击单元格的情况
DataGridViewRow gridViewRow = this.Rows[gridViewHitTestInfo.RowIndex];
int intSelRowsCount = this.SelectedRows.Count;
if (gridViewRow != null)
{
if (_isShowDelete)
{
if (1 == intSelRowsCount)
{
_ctxCell.Items.Clear();
// 设定右键菜单的Item
if (this.ContextMenuVisible != ContextMenuVisibleFlags.None)
{
AddToolStripSeparator(_ctxCell);
_ctxCell.Items.Add(this._mnuDelete);
}
Point point = new Point(e.X, e.Y);
point = this.PointToScreen(point);
_ctxCell.Tag = gridViewHitTestInfo;
_ctxCell.Show(point);
}
}
else
{
if (!_isCanDelete)
{
if (!gridViewRow.IsNewRow)
{
this.Tag = false;
this.CurrentCell = gridViewRow.Cells[gridViewHitTestInfo.ColumnIndex];
this.Tag = true;
// 点击右键要调到相应的行去 周兴 2016-11-3 修改
if (IsOpenMergeCellFlag )
{
this.OnSelectionChanged(e);
}
}
// 设定右键菜单的Item
SetGridViewCellMenu(gridViewRow);
Point point = new Point(e.X, e.Y);
point = this.PointToScreen(point);
_ctxCell.Tag = gridViewHitTestInfo;
_ctxCell.Show(point);
_gridRowIndex = gridViewHitTestInfo.RowIndex;
_gridColumnindex = gridViewHitTestInfo.ColumnIndex;
}
}
}
}
}
catch (Exception ex)
{
throw ex;
// todo 捕获之后不操作
}
}
#endregion
#region 行事件
private void dkDataGridView_RowEnter(object sender, DataGridViewCellEventArgs e)
{
DataGridViewRow currentRow = ((DataGridView)sender).Rows[e.RowIndex];
if (currentRow != null)
{
if (!currentRow.IsNewRow)
{
if (currentRow.ReadOnly != !_isAllowUserToModifyRows)
{
currentRow.ReadOnly = !_isAllowUserToModifyRows;
}
}
}
if (this.IsCurrentCellDirty)
{
this.NotifyCurrentCellDirty(false);
}
}
private void Rows_CollectionChanged(object sender,
System.ComponentModel.CollectionChangeEventArgs e)
{
switch (e.Action)
{
case System.ComponentModel.CollectionChangeAction.Refresh:
if (this.Rows.Count > 0)
{
SetBackColorCell(-1, -1);
}
break;
case System.ComponentModel.CollectionChangeAction.Add:
break;
case System.ComponentModel.CollectionChangeAction.Remove:
break;
}
}
private void dkDataGridView_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
SetBackColorCell(e.RowIndex, -1);
}
#endregion
#region 鼠标、键盘事件
private void dkDataGridView_MouseDown(object sender, MouseEventArgs e)
{
DataGridView.HitTestInfo gridViewHitTestInfo = this.HitTest(e.X, e.Y);
if (gridViewHitTestInfo.Type == DataGridViewHitTestType.None)
{
if (this.IsClearSelected)
{
// 清除选择行
this.ClearSelection();
}
this.labelHideFocus.Focus();
if (MouseClickOnSpace != null)
{
MouseClickOnSpace(this, e);
}
return;
}
if ((e.Button & MouseButtons.Right) == MouseButtons.Right)
{
// 右键点击
DataGridViewMouseDownRight(gridViewHitTestInfo, e);
SetMnuFrozenText(gridViewHitTestInfo.RowIndex, gridViewHitTestInfo.ColumnIndex);
}
}
///
/// 按下ESC键的处理
///
///
///
private void dkDataGridView_EscKeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape)
{
if (this.IsClearSelected)
{
this.ClearSelection();
this.labelHideFocus.Focus();
if (MouseClickOnSpace != null)
{
MouseClickOnSpace(this, e);
}
}
}
}
private void AddToolStripSeparator(ContextMenuStrip contextMenuStrip)
{
if (contextMenuStrip.Items.Count == 0)
{
return;
}
if (contextMenuStrip.Items[contextMenuStrip.Items.Count - 1] is ToolStripSeparator)
{
return;
}
contextMenuStrip.Items.Add(new ToolStripSeparator());
}
private void dkDataGridView_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
((DataGridView)sender).EndEdit();
}
#endregion
#region 右键菜单事件
private void mnuRefine_RefineTextFixed(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(_mnuRefine.Text))
{
MessageBox.Show(ControlsTips.DK_DataGridView_RefineEmpty);
}
else
{
ToolStripItem toolStripItem = sender as ToolStripItem;
if (toolStripItem == null)
{
return;
}
ContextMenuStrip contextMenuStrip = toolStripItem.Owner as ContextMenuStrip;
if (contextMenuStrip == null)
{
return;
}
contextMenuStrip.Close();
HitTestInfo info = (HitTestInfo)contextMenuStrip.Tag;
this.Tag = false;
this.FilterRow(info.ColumnIndex, FilterType.Like, _mnuRefine.Text);
this.Tag = true;
this.OnSelectionChanged(e);
}
}
protected String ConvertRegularExpressionFilter(String sqlFilter)
{
if (String.IsNullOrEmpty(sqlFilter))
{
return sqlFilter;
}
if ("%".Equals(sqlFilter))
{
return ".";
}
Boolean isStartVague = (sqlFilter.Substring(0, 1) == "%");
Boolean isEndVague = (sqlFilter.Substring(sqlFilter.Length - 1, 1) == "%");
String escapedSqlFilter = sqlFilter.Substring((isStartVague) ? 1 : 0,
sqlFilter.Length - ((isEndVague) ? 1 : 0) - ((isStartVague) ? 1 : 0));
return String.Format("{0}{1}{2}", isStartVague ? String.Empty : "%",
escapedSqlFilter, isEndVague ? String.Empty : "%");
}
private void mnuFilter_Click(object sender, EventArgs e)
{
this.Tag = false;
this.FilterRow(FilterType.Equal);
this.Tag = true;
this.OnSelectionChanged(e);
}
private void mnuFilterExcept_Click(object sender, EventArgs e)
{
this.Tag = false;
this.FilterRow(FilterType.NotEqual);
this.Tag = true;
this.OnSelectionChanged(e);
}
private void mnuUnfilter_Click(object sender, EventArgs e)
{
this.Tag = false;
this.ResetFilter();
this.Tag = true;
this.OnSelectionChanged(e);
}
private void mnuOutputFile_Click(object sender, EventArgs e)
{
this.OutputFile();
}
private void mnuOutputFileXls_Click(object sender, EventArgs e)
{
this.OutputFileXls();
}
private void mnuFrozen_Click(object sender, EventArgs e)
{
this.Tag = false;
this.SetFrozen();
this.Tag = true;
}
private void mnuDelete_Click(object sender, EventArgs e)
{
if (RowsHeaderClick != null)
{
RowsHeaderClick(this, e);
}
}
private void mnuPrint_Click(object sender, EventArgs e)
{
VBprinter.DGVprint dGVprint = new VBprinter.DGVprint();
dGVprint.PrintType = VBprinter.DGVprint.mytype.GeneralPrint;//打印对齐
dGVprint.Alignment = StringAlignment.Center; //表格居中
dGVprint.MainTitle = this.Text;//主标题
dGVprint.AutoFormat = false;//自动调整行宽
dGVprint.IsShowUnvisibleColum = false;//是否显示隐藏列
if (this.ColumnTreeView == null || this.ColumnTreeView.Length == 0)
{
dGVprint.Print(this, true, "");
}
else
{
dGVprint.Print(this, true, "", this.ColumnTreeView[0]);
}
}
#endregion
#region dkDataGridView事件
private void dkDataGridView_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
if (e.Context == DataGridViewDataErrorContexts.Commit)
{
e.Cancel = true;
}
}
private void dkDataGridView_ReadOnlyChanged(object sender, EventArgs e)
{
SetBackColorCell(-1, -1);
}
private void dkDataGridView_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
if (e.KeyCode == Keys.Escape)
{
if (this.DataSource != null)
{
if (this.BindingContext[this.DataSource, this.DataMember].Count ==
1 && this.CurrentRow.IsNewRow)
{
this.BindingContext[this.DataSource, this.DataMember].RemoveAt(0);
}
}
}
}
private void dkDataGridView_EditingControlShowing(object sender,
DataGridViewEditingControlShowingEventArgs e)
{
if (this.EditingControl != null)
{
this.EditingControl.PreviewKeyDown -=
new PreviewKeyDownEventHandler(EditingControl_PreviewKeyDown);
this.EditingControl.PreviewKeyDown +=
new PreviewKeyDownEventHandler(EditingControl_PreviewKeyDown);
}
}
private void EditingControl_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
if (e.KeyCode == Keys.Escape)
{
if (this.DataSource != null)
{
if (this.BindingContext[this.DataSource, this.DataMember].Count ==
1 && this.CurrentRow.IsNewRow)
{
this.BindingContext[this.DataSource, this.DataMember].RemoveAt(0);
}
}
}
}
#endregion
#endregion
#region 设计自动生成代码
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle3 = new System.Windows.Forms.DataGridViewCellStyle();
this._ctxColumnHeader = new System.Windows.Forms.ContextMenuStrip(this.components);
this._ctxCell = new System.Windows.Forms.ContextMenuStrip(this.components);
this.labelHideFocus = new System.Windows.Forms.Label();
((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
this.SuspendLayout();
//
// _ctxColumnHeader
//
this._ctxColumnHeader.Name = "contextMenuStrip1";
this._ctxColumnHeader.Size = new System.Drawing.Size(61, 4);
//
// _ctxCell
//
this._ctxCell.Name = "ctxCell";
this._ctxCell.Size = new System.Drawing.Size(61, 4);
//
// labelHideFocus
//
this.labelHideFocus.AutoSize = true;
this.labelHideFocus.Location = new System.Drawing.Point(0, 0);
this.labelHideFocus.Name = "labelHideFocus";
this.labelHideFocus.Size = new System.Drawing.Size(0, 12);
this.labelHideFocus.TabIndex = 0;
//
// dkDataGridView
//
dataGridViewCellStyle1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(235)))), ((int)(((byte)(235)))), ((int)(((byte)(235)))));
this.AlternatingRowsDefaultCellStyle = dataGridViewCellStyle1;
this.ColumnHeadersBorderStyle = System.Windows.Forms.DataGridViewHeaderBorderStyle.Single;
dataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
dataGridViewCellStyle2.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(48)))), ((int)(((byte)(58)))), ((int)(((byte)(70)))));
dataGridViewCellStyle2.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
dataGridViewCellStyle2.ForeColor = System.Drawing.Color.White;
dataGridViewCellStyle2.SelectionBackColor = System.Drawing.SystemColors.Highlight;
dataGridViewCellStyle2.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
dataGridViewCellStyle2.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
this.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle2;
this.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.EnableResizing;
this.ColumnHeadersHeight = 25;
this.Controls.Add(this.labelHideFocus);
this.EnableHeadersVisualStyles = false;
dataGridViewCellStyle3.SelectionBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(159)))), ((int)(((byte)(39)))), ((int)(((byte)(39)))));
this.RowsDefaultCellStyle = dataGridViewCellStyle3;
this.RowTemplate.Height = 25;
this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.dkDataGridView_MouseDown);
this.RowEnter += new System.Windows.Forms.DataGridViewCellEventHandler(this.dkDataGridView_RowEnter);
this.ColumnHeaderMouseClick += new System.Windows.Forms.DataGridViewCellMouseEventHandler(this.dkDataGridView_ColumnHeaderMouseClick);
this.ReadOnlyChanged += new System.EventHandler(this.dkDataGridView_ReadOnlyChanged);
this.CellValidated += new System.Windows.Forms.DataGridViewCellEventHandler(this.dkDataGridView_CellValidated);
this.RowPostPaint += new System.Windows.Forms.DataGridViewRowPostPaintEventHandler(this.dkDataGridView_RowPostPaint);
this.PreviewKeyDown += new System.Windows.Forms.PreviewKeyDownEventHandler(this.dkDataGridView_PreviewKeyDown);
this.CellEndEdit += new System.Windows.Forms.DataGridViewCellEventHandler(this.dkDataGridView_CellEndEdit);
this.EditingControlShowing += new System.Windows.Forms.DataGridViewEditingControlShowingEventHandler(this.dkDataGridView_EditingControlShowing);
this.DataError += new System.Windows.Forms.DataGridViewDataErrorEventHandler(this.dkDataGridView_DataError);
this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.dkDataGridView_EscKeyDown);
this.CellEnter += new System.Windows.Forms.DataGridViewCellEventHandler(this.dkDataGridView_CellEnter);
this.RowHeaderMouseClick += new System.Windows.Forms.DataGridViewCellMouseEventHandler(this.dkDataGridView_RowHeaderMouseClick);
((System.ComponentModel.ISupportInitialize)(this)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
private void dkDataGridView_ColumnHeaderMouseClick(object sender,
DataGridViewCellMouseEventArgs e)
{
string sort = "ASC";
string sortColumns = "";
int columnIndex = e.ColumnIndex;
DataGridViewColumn column = this.Columns[columnIndex];
string colName = column.Name;
string colPropertyName = column.DataPropertyName;
if (this.AllowUserToSortRows == false)
{
return;
}
if (columnIndex < 0 || this.Columns.Count <= columnIndex)
{
throw new ArgumentException("列索引超出范围。");
}
if (string.IsNullOrEmpty(colPropertyName))
{
return;
}
// 点击同一列进行排序时,切换升序和降序
if (colName.Equals(_sortColumnName))
{
if (_sortOrderType == SortOrder.Ascending)
{
_sortOrderType = SortOrder.Descending;
sort = "DESC";
}
else
{
_sortOrderType = SortOrder.Ascending;
sort = "ASC";
}
}
else
{
// 不是同一列进行排序时,按升序排序
_sortOrderType = SortOrder.Ascending;
_sortColumnName = colName;
sort = "ASC";
}
if (!string.IsNullOrEmpty(SortOrderColumnName))
{
sortColumns = this.AnalysisSortColumn(_sortColumnName, sort);
if (!string.IsNullOrEmpty(sortColumns))
{
DataTable dataTable = (DataTable)this.DataSource;
DataView dataView = dataTable.DefaultView;
dataView.Sort = sortColumns;
this.DataSource = dataView.Table;
this.Columns[_sortColumnName].HeaderCell.SortGlyphDirection = _sortOrderType;
}
}
this.OnSelectionChanged(e);
}
private string AnalysisSortColumn(string currentColumn, string sortDirection)
{
string retColumn = "";
string[] orderColumn = this.SortOrderColumnName.Split(';');
int i = 0;
for (i = 0; i < orderColumn.Length; i++)
{
string[] tmpColumn = orderColumn[i].Split(':');
if (currentColumn.Equals(tmpColumn[0]))
{
retColumn = tmpColumn[1];
break;
}
}
string[] sortCols = retColumn.Split(',');
retColumn = sortCols[0] + " " + sortDirection;
for (i = 1; i < sortCols.Length; i++)
{
retColumn = retColumn + "," + sortCols[0] + " " + sortDirection;
}
return retColumn;
}
#endregion
}
#region 剪贴板处理
public partial class dkDataGridView
{
#region 成员变量
private ClipboardType _clipboardType = ClipboardType.InnerAndDisp;
#endregion
#region 属性
[System.ComponentModel.DefaultValue(ClipboardType.InnerAndDisp)]
public ClipboardType ClipboardType
{
get
{
return _clipboardType;
}
set
{
_clipboardType = value;
}
}
#endregion
#region 重写方法/函数
protected override void OnSizeChanged(EventArgs e)
{
try
{
if (_isOpenTotalRow)
{
SetTxtTop();
SetTxtLeft();
}
base.OnSizeChanged(e);
}
catch (Exception ex)
{
throw ex;
}
}
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
//if (keyData == Keys.Enter)
//{
// SendKeys.Send("{Tab}");
// return true;
//}
const int WM_KEYDOWN = 0x0100;
const int WM_KEYUP = 0x0101;
Keys keyCode = (Keys)(int)keyData & Keys.KeyCode;
switch (msg.Msg)
{
case WM_KEYDOWN:
break;
case WM_KEYUP:
if (keyCode == Keys.Delete)
{
if (this.ReadOnly || !this.Enabled)
{
return true;
}
if (0 == this.SelectedRows.Count)
{
if (this.EditingControl != null)
{
break;
}
DataGridViewCell cell = this.CurrentCell;
if (cell != null && !cell.ReadOnly)
{
if (!Utility.IsNull(cell.Value))
{
if (this.BeginEdit(false))
{
if (this.EditingControl != null)
{
this.EditingControl.Text = null;
}
this.EndEdit();
}
}
}
}
else
{
if (this.AllowUserToDeleteRows)
{
return false;
}
}
}
else if (keyCode == Keys.Escape)
{
return false;
}
break;
}
return base.ProcessCmdKey(ref msg, keyData);
}
#endregion
#region 公开方法/函数
public bool IsCopyData()
{
// DataTable信息转换成csv形式
string csvInner = null;
string csvDisp = null;
if (this.ClipboardType == ClipboardType.InnerAndDisp)
{
csvInner = ToCsvString(false, true, false, false);
csvDisp = ToCsvString(true, true, true, false);
}
else
{
csvInner = ToCsvString(false, true, false, false);
csvDisp = csvInner;
}
if (string.IsNullOrEmpty(csvDisp) || string.IsNullOrEmpty(csvInner))
{
return false;
}
// 往剪贴板上拷贝数据
DataObject dataObject = new DataObject();
dataObject.SetData(DataFormats.Text, csvDisp);
dataObject.SetData(ControlsConst.CLIPBOARD_FORMAT, csvInner);
Clipboard.SetDataObject(dataObject, true);
return true;
}
public bool IsPasteData()
{
if (this.ReadOnly || !this.Enabled)
{
// 不允许粘贴
return true;
}
if (this.CurrentCell != null)
{
if (this.CurrentCell.IsInEditMode && !(
this.CurrentCell is DataGridViewCheckBoxCell))
{
return false;
}
}
if (CurrentDataTable == null)
{
return false;
}
DataColumnCollection columns = CurrentDataTable.Columns;
IDataObject dataObject = Clipboard.GetDataObject();
// 剪贴板的CVS数据转换成DataTable
DataTable tableCsv = null;
object data = dataObject.GetData(ControlsConst.CLIPBOARD_FORMAT);
if (data == null)
{
if (dataObject.GetDataPresent(DataFormats.Text, true))
{
data = dataObject.GetData(DataFormats.Text, true);
if (data == null)
{
return true;
}
}
}
string csv = data.ToString();
tableCsv = CsvManager.ToDataTable(csv, false, '\t', '\"');
if (tableCsv == null)
{
return true;
}
List columnIndexList;
int rowIndexMin, rowIndexMax;
GetSelectedRange(out columnIndexList, out rowIndexMin, out rowIndexMax);
// 设置DataColumn信息
DataTable table = new DataTable();
foreach (int columnIndex in columnIndexList)
{
DataGridViewColumn column = this.Columns[columnIndex];
if (column == null)
{
return true;
}
if (column.CellType.Name == "DataGridViewSearchFileBoxCellEx")
{
continue;
}
table.Columns.Add(column.DataPropertyName);
}
DataRowView rowView;
DataRow drowRow;
int rowCount = tableCsv.Rows.Count;
int viewRowCount = Rows.Count;
int columnCount = tableCsv.Columns.Count;
int j = 0;
for (int i = rowIndexMin; i <= rowIndexMax; i++)
{
try
{
if (columnIndexList.Count < Columns.Count)
{
if (!Rows[i].IsNewRow)
{
rowView = GetDataRowView(i);
if (rowView == null)
{
continue;
}
for (int k = 0; k < columnIndexList.Count; k++)
{
int columnIndex = columnIndexList[k];
if (!this.Rows[i].Cells[columnIndex].ReadOnly)
{
rowView[this.Columns[columnIndex].DataPropertyName] =
ConvertValue(tableCsv.Rows[j][k].ToString());
}
}
j++;
}
else
{
for (; j < rowCount; j++)
{
drowRow = CurrentDataTable.NewRow();
for (int k = 0; k < columnIndexList.Count; k++)
{
int columnIndex = columnIndexList[k];
if (!this.Rows[i].Cells[columnIndex].ReadOnly)
{
drowRow[this.Columns[columnIndex].DataPropertyName] =
ConvertValue(tableCsv.Rows[j][k].ToString());
}
}
CurrentDataTable.Rows.Add(drowRow);
}
this.Rows.RemoveAt(this.CurrentCell.RowIndex);
}
}
else
{
if (!Rows[i].IsNewRow)
{
rowView = GetDataRowView(i);
if (rowView == null)
{
continue;
}
for (int k = 0; k < columnCount; k++)
{
try
{
if (!this.Rows[i].Cells[k].ReadOnly)
{
rowView[table.Columns[k].ColumnName] =
ConvertValue(tableCsv.Rows[j][k].ToString());
}
}
catch (ReadOnlyException)
{
}
}
rowView.EndEdit();
j++;
if (rowCount <= j)
{
break;
}
}
else
{
for (; j < rowCount; j++)
{
drowRow = CurrentDataTable.NewRow();
for (int k = 0; k < columnCount; k++)
{
try
{
if (!this.Rows[i].Cells[k].ReadOnly)
{
drowRow[table.Columns[k].ColumnName] =
ConvertValue(tableCsv.Rows[j][k].ToString());
}
}
catch (ReadOnlyException)
{
}
}
CurrentDataTable.Rows.Add(drowRow);
}
}
}
}
catch (IndexOutOfRangeException)
{
break;
}
catch (Exception ex)
{
Debug.Assert(false, "错误", ex.Message);
MessageBox.Show(ex.Message);
return true;
}
}
if (CurrentDataTable != null && CurrentDataTable.Rows.Count + 2 == this.Rows.Count)
{
this.Rows.RemoveAt(this.Rows.Count - 2);
}
if (this.CurrentCell != null)
{
this.Refresh();
}
return true;
}
///
/// 打开合计行
///
public void OpenTotalRow()
{
try
{
_isOpenTotalRow = true;
NewText(string.Empty, 0);//设置RowHeader对应的TextBox;
SetTxtLeft();
SetTxtTop();
this.HorizontalScrollBar.VisibleChanged += new EventHandler(HorizontalScrollBar_VisibleChanged);//水平
this.VerticalScrollBar.VisibleChanged += new EventHandler(VerticalScrollBar_VisibleChanged); //竖直
this.HorizontalScrollBar.ValueChanged += new EventHandler(HorizontalScrollBar_ValueChanged);
_columnInfos = this.GetDataGridViewColumnInfos();
if (_columnInfos != null)
{
for (int i = 0; i < _columnInfos.Length; i++)
{
if (_columnInfos[i].Visible)
{
NewText(_columnInfos[i].DataPropertyName, i);
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
void HorizontalScrollBar_ValueChanged(object sender, EventArgs e)
{
try
{
SetTxtLeft();
}
catch (Exception ex)
{
throw ex;
}
}
void VerticalScrollBar_VisibleChanged(object sender, EventArgs e)
{
try
{
if (VerticalScrollBar.Visible)
{
int width = 0;
if (findTextBox("txt" + this.Name) != null)
{
width = findTextBox("txt" + this.Name).Width;
}
this.VerticalScrollBar.Maximum = this.VerticalScrollBar.Maximum + width;
}
}
catch (Exception ex)
{
throw ex;
}
}
void HorizontalScrollBar_VisibleChanged(object sender, EventArgs e)
{
try
{
SetTxtTop();
}
catch (Exception ex)
{
throw ex;
}
}
//求和
protected override void OnCellEndEdit(DataGridViewCellEventArgs e)
{
if (_isOpenTotalRow && IsAutoCountSum)
{
if (this.dt == null) return;
string s = this.CurrentCell.Value + "";
bool isValue = false;
foreach (DataColumn dc in dt.Columns)
{
if (dc.ColumnName == this.Columns[e.ColumnIndex].DataPropertyName)
{
if (TotalSumColumns != null && TotalSumColumns.Count > 0)
{
if (TotalSumColumns.Contains(dc.ColumnName))
{
isValue = dc.DataType.IsValueType;
break;
}
}
else
{
isValue = dc.DataType.IsValueType;
break;
}
}
}
decimal sumValue = 0;
if (isValue)
{
try
{
if (this.Columns[e.ColumnIndex].Visible)
{
object o = dt.Compute("SUM(" + this.Columns[e.ColumnIndex].DataPropertyName + ")", filter);
decimal.TryParse(o.ToString(), out sumValue);
string format = "F0";
if (!string.IsNullOrEmpty(this.Columns[e.ColumnIndex].DefaultCellStyle.Format))
{
format = this.Columns[e.ColumnIndex].DefaultCellStyle.Format;
}
if (IsSubTotalFlag)
{
if (!this.Columns[e.ColumnIndex].Name.Contains("Box") &&
!this.Columns[e.ColumnIndex].Name.Contains("Piece"))
{
findTextBox("txt" + this.Columns[e.ColumnIndex].Name.ToString()).Text
= (sumValue / 2).ToString(format);
}
else
{
findTextBox("txt" + this.Columns[e.ColumnIndex].Name.ToString()).Text
= sumValue.ToString(format);
}
}
else
{
findTextBox("txt" + this.Columns[e.ColumnIndex].Name.ToString()).Text
= sumValue.ToString(format);
}
}
}
catch (DataException)
{ }
}
}
base.OnCellEndEdit(e);
}
protected override void OnDataSourceChanged(EventArgs e)
{
try
{
base.OnDataSourceChanged(e);
if (_isOpenTotalRow)
{
if (dt == null || _columnInfos == null) return;
// 解决合计行遮住最后一行的bug
if (dt.Rows.Count > 0)
{
int height = dt.Rows.Count * this.CellHeight + this.ColumnHeadersHeight;
if (findTextBox("txt" + this.Name) != null)
{
height += findTextBox("txt" + this.Name).Height;
}
if (height > this.Height)
{
if (!this.AllowUserToAddRows)
{
this.AllowUserToAddRows = true;
this.ReadOnly = true;
}
}
else
{
if (this.AllowUserToAddRows)
{
this.AllowUserToAddRows = false;
}
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
///
/// 重新计算合计行
///
public void CountTotalRow()
{
try
{
if (_isOpenTotalRow)
{
if (dt == null || _columnInfos == null) return;
//for (int j = 0; j < dt.Rows.Count; j++)
//{
// for (int i = 0; i < dt.Columns.Count; i++)
// {
// if (("Decimal".Equals(dt.Columns[i].DataType.Name)
// || "Int".Equals(dt.Columns[i].DataType.Name)
// || "Double".Equals(dt.Columns[i].DataType.Name)))
// {
// DataGridViewCell cell = this.Rows[this.Rows.Count - 1].Cells[dt.Columns[i].ColumnName];
// dt.Rows[j][i] = cell.FormattedValue;
// }
// }
//}
// 解决合计行遮住最后一行的bug
//if (dt.Rows.Count > 0)
//{
// int height = dt.Rows.Count * this.CellHeight + this.ColumnHeadersHeight + findTextBox("txt").Height;
// if (height > this.Height)
// {
// if (!this.AllowUserToAddRows)
// {
// this.AllowUserToAddRows = true;
// this.ReadOnly = true;
// }
// }
// else
// {
// if (this.AllowUserToAddRows)
// {
// this.AllowUserToAddRows = false;
// }
// }
//}
string totalCountNameFormat = string.Empty;
for (int i = 0; i < _columnInfos.Length; i++)
{
if (!string.IsNullOrEmpty(TotalCountName) && TotalCountName.Equals(_columnInfos[i].DataPropertyName))
{
totalCountNameFormat = _columnInfos[i].DefaultCellStyle.Format;
}
bool isValue = false;
foreach (DataColumn dc in dt.Columns)
{
if (dc.ColumnName == _columnInfos[i].DataPropertyName)
{
if (TotalSumColumns != null && TotalSumColumns.Count > 0)
{
if (TotalSumColumns.Contains(dc.ColumnName))
{
isValue = dc.DataType.IsValueType;
break;
}
}
else
{
isValue = dc.DataType.IsValueType;
break;
}
}
}
decimal sumValue = 0;
if (isValue)
{
try
{
if (_columnInfos[i].Visible)
{
object o = dt.Compute("SUM([" + _columnInfos[i].DataPropertyName + "])", filter);
decimal.TryParse(o.ToString(), out sumValue);
TextBox tb = findTextBox("txt" + _columnInfos[i].DataPropertyName);
if (tb != null)
{
if (dt.Rows.Count == 0 && sumValue == 0)
{
tb.Text = string.Empty;
}
else
{
// 周兴 2016-10-10 修改 合计行去掉小数位数后多余的0
//if (!string.IsNullOrEmpty(_columnInfos[i].DefaultCellStyle.Format))
//{
// if (IsSubTotalFlag)
// {
// if (!_columnInfos[i].DataPropertyName.Contains("Box") &&
// !_columnInfos[i].DataPropertyName.Contains("Piece"))
// {
// tb.Text = (sumValue / 2).ToString(_columnInfos[i].DefaultCellStyle.Format);
// }
// else
// {
// tb.Text = sumValue.ToString(_columnInfos[i].DefaultCellStyle.Format);
// }
// }
// else
// {
// tb.Text = sumValue.ToString(_columnInfos[i].DefaultCellStyle.Format);
// }
//}
//else
//{
// if (IsSubTotalFlag)
// {
// if (!_columnInfos[i].DataPropertyName.Contains("Box") &&
// !_columnInfos[i].DataPropertyName.Contains("Piece"))
// {
// tb.Text = (sumValue / 2) + "";
// }
// else
// {
// tb.Text = sumValue + "";
// }
// }
// else
// {
// tb.Text = sumValue + "";
// }
//}
if (IsSubTotalFlag)
{
if (!_columnInfos[i].DataPropertyName.Contains("Box") &&
!_columnInfos[i].DataPropertyName.Contains("Piece"))
{
tb.Text = (sumValue / 2).ToString("####.######");
}
else
{
tb.Text = sumValue.ToString("####.######");
}
}
else
{
tb.Text = sumValue.ToString("####.######");
}
}
}
}
}
catch (DataException)
{ }
}
}
// 用合计的值进行重新计算
if (!string.IsNullOrEmpty(TotalCountName))
{
if (!string.IsNullOrEmpty(TotalCountFormula))
{
if (TotalCountFormula.IndexOf("|") >= 0)
{
string[] formulas = TotalCountFormula.Split('|');
string formula = formulas[0];
string formula1 = formulas[1]; // A1:ss,A2:tt
string[] formula2s = formula1.Split(',');
TextBox tb = null;
TextBox tboo = findTextBox("txt" + TotalCountName);
if (tboo != null)
{
for (int i = 0; i < formula2s.Length; i++)
{
string[] ss = formula2s[i].Split(':');
tb = findTextBox("txt" + ss[1]);
if (tb != null && !string.IsNullOrEmpty(tb.Text))
{
formula = formula.Replace(ss[0], tb.Text);
}
else
{
tboo.Text = string.Empty;
break;
}
}
try
{
// 计算值
MSScriptControl.ScriptControl sc = new MSScriptControl.ScriptControlClass();
sc.Language = "JavaScript";
string result = sc.Eval(formula) + "";
if (!string.IsNullOrEmpty(result))
{
tboo.Text = Convert.ToDecimal(result).ToString("F2");
}
}
catch (Exception)
{
tboo.Text = string.Empty;
}
}
}
TextBox tbo = findTextBox("txt" + TotalCountName);
try
{
string fomulastring = TotalCountFormula;
string[] formula = fomulastring.Split(new char[] { '+', '-', '*', '/', '(', ')' });
TextBox tb = null;
for (int i = 0; i < formula.Length; i++)
{
tb = findTextBox("txt" + formula[i]);
if (tb != null && !string.IsNullOrEmpty(tb.Text))
{
fomulastring = fomulastring.Replace(formula[i], tb.Text);
}
else
{
tbo.Text = string.Empty;
break;
}
}
// 计算值
MSScriptControl.ScriptControl sc = new MSScriptControl.ScriptControlClass();
sc.Language = "JavaScript";
string result = sc.Eval(fomulastring) + "";
if (!string.IsNullOrEmpty(result))
{
if (string.IsNullOrEmpty(totalCountNameFormat))
{
totalCountNameFormat = "####.######";
}
tbo.Text = Convert.ToDecimal(result).ToString(totalCountNameFormat);
}
}
catch (Exception)
{
tbo.Text = string.Empty;
}
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
///
/// 清除合计行
///
public void ClearTotalRow()
{
try
{
//if (_columnInfos != null)
//{
// //for (int i = 0; i < _columnInfos.Length; i++)
// //{
// // this.Controls.RemoveByKey("txt" + _columnInfos[i].DataPropertyName);
// //}
//}
for (int i = this.Controls.Count - 1; i >= 0; i--)
{
if (this.Controls[i].Name.StartsWith("txt") && !"txt".Equals(this.Controls[i].Name))
{
this.Controls.RemoveAt(i);
}
}
}
catch (Exception ex)
{
throw ex;
}
}
///
/// 清除合计行
///
public void ClearTotalRowData()
{
try
{
for (int i = this.Controls.Count - 1; i >= 0; i--)
{
if (this.Controls[i].Name.StartsWith("txt") && !"txt".Equals(this.Controls[i].Name))
{
TextBox tb = this.Controls[i] as TextBox;
if (tb != null)
{
tb.Clear();
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
///
/// 重新生成合计行并计算合计行
///
public void CountNewTextAndTotalRow()
{
try
{
if (_columnInfos != null)
{
for (int i = 0; i < _columnInfos.Length; i++)
{
this.Controls.RemoveByKey("txt" + _columnInfos[i].DataPropertyName);
}
}
_isOpenTotalRow = true;
_columnInfos = GetDataGridViewColumnInfos();
if (_columnInfos != null)
{
this.HorizontalScrollingOffset = 0;
NewText(string.Empty, 0);
for (int i = 0; i < _columnInfos.Length; i++)
{
if (_columnInfos[i].Visible)
{
NewText(_columnInfos[i].DataPropertyName, i);
}
}
CountTotalRow();
}
IsAutoResizeColumns = false;
}
catch (Exception ex)
{
throw ex;
}
}
//设置TextBox的Top,使之保持在DagtaGridView最下方;
private void SetTxtTop()
{
try
{
if (_columnInfos == null) return;
int topTxt = 0;
if (HorizontalScrollBar.Visible)
topTxt = this.Height - this.HorizontalScrollBar.Height;
else
topTxt = this.Height;
TextBox t = findTextBox("txt" + this.Name);
if (t != null)
{
t.Top = topTxt - t.Height;
for (int i = 0; i < _columnInfos.Length; i++)
{
if (this._columnInfos[i].Visible)
{
TextBox t1 = findTextBox("txt" + this._columnInfos[i].DataPropertyName);
if (t1 != null)
{
t1.Top = t.Top;
t1.TextAlign = HorizontalAlignment.Right;
}
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
//根据TextBox的名字找到TextBox;
private TextBox findTextBox(string txtName)
{
try
{
foreach (Control ctl in this.Controls)
{
if (ctl.Name == txtName)
return ctl as TextBox;
}
return null;
}
catch (Exception ex)
{
throw ex;
}
}
//设置TextBox的Left,使之与对应的Column的Left对应
private void SetTxtLeft()
{
try
{
if (_columnInfos == null) return;
int left = 0;
bool flag = false;
if (!_isFrozen)
{
flag = true;
}
for (int i = 0; i < _columnInfos.Length; i++)
{
if (_isFrozen)
{
if (!_columnInfos[i].Frozen)
{
flag = true;
}
}
if (flag)
{
TextBox tt = findTextBox("txt" + this._columnInfos[i].DataPropertyName);
if (tt != null)
{
left = getLeft(_columnInfos[i].DataPropertyName, i);
if (left < RowHeadersWidth - HorizontalScrollingOffset)
{
tt.Visible = false;
}
else
{
tt.TextAlign = HorizontalAlignment.Right;
tt.Visible = true;
tt.Left = left;
}
}
}
}
//for (int i = 0; i < this.FirstDisplayedScrollingColumnIndex; i++)
//{
// TextBox tt = findTextBox("txt" + this._columnInfos[i].DataPropertyName);
// if (tt != null)
// {
// tt.Visible = false;
// }
//}
//int firstIndex = FirstDisplayedScrollingColumnIndex > 0 ? FirstDisplayedScrollingColumnIndex : 0;
//for (int j = firstIndex; j < _columnInfos.Length; j++)
//{
// if (_columnInfos != null && _columnInfos[j].Visible)
// {
// TextBox t = findTextBox("txt" + _columnInfos[j].DataPropertyName);
// if (t != null)
// {
// t.TextAlign = HorizontalAlignment.Right;
// t.Visible = true;
// t.Left = getLeft(_columnInfos[j].DataPropertyName, j);
// }
// }
//}
}
catch (Exception ex)
{
throw ex;
}
}
//得到Column的Left
public int getLeft(string columnName, int endIndex)
{
try
{
if (string.IsNullOrEmpty(columnName) || _columnInfos == null) return 0;
int left = this.RowHeadersWidth;
//int left = this.RowHeadersWidth - this.FirstDisplayedScrollingColumnHiddenWidth;
//int firstIndex = FirstDisplayedScrollingColumnIndex > 0 ? FirstDisplayedScrollingColumnIndex : 0;
//for (int i = firstIndex; i < infos[columnName].Index; i++)
//{
// left += Columns[i].Width;
//}
for (int i = 0; i < endIndex; i++)
{
left += _columnInfos[i].Width;
}
left -= this.HorizontalScrollingOffset;
return left;
}
catch (Exception ex)
{
throw ex;
}
}
//生成TextBox;
private void NewText(string columnName, int columnIndex)
{
try
{
TextBox t = new TextBox();
t.ReadOnly = true;
if (string.IsNullOrEmpty(columnName))
{
TextBox t1 = findTextBox("txt" + this.Name);
if (t1 == null)
{
t.Name = "txt" + this.Name;
t.Width = this.RowHeadersWidth;
t.Text = "合计";
}
else
{
return;
}
}
else
{
t.TextAlign = HorizontalAlignment.Right;
t.Name = "txt" + columnName;
t.Width = _columnInfos[columnIndex].Width;
}
t.BackColor = System.Drawing.Color.LightBlue;
int topTxt = 0;
if (HorizontalScrollBar.Visible)
topTxt = this.Height - this.HorizontalScrollBar.Height;
else
topTxt = this.Height;
t.Top = topTxt - t.Height;
t.Left = getLeft(columnName, columnIndex);
if (findTextBox(t.Name) == null)
{
this.Controls.Add(t);
t.Show();
}
else
{
if (!("txt" + this.Name).Equals(t.Name))
{
this.Controls.RemoveByKey(t.Name);
this.Controls.Add(t);
t.Show();
}
else
{
this.Controls.Add(t);
t.Show();
}
}
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region 受保护的方法/函数
protected void GetSelectedRange(out List columnIndexList,
out int rowIndexMin, out int rowIndexMax)
{
List list = new List();
columnIndexList = new List();
rowIndexMin = -1;
rowIndexMax = -1;
foreach (DataGridViewCell cell in this.SelectedCells)
{
if (rowIndexMin < 0)
{
// 第一次的情况
rowIndexMin = cell.RowIndex;
rowIndexMax = cell.RowIndex;
}
else
{
// 第一次以后的情况
if (cell.RowIndex < rowIndexMin)
{
rowIndexMin = cell.RowIndex;
}
if (rowIndexMax < cell.RowIndex)
{
rowIndexMax = cell.RowIndex;
}
}
if (!list.Contains(cell.ColumnIndex))
{
list.Add(cell.ColumnIndex);
}
}
while (true)
{
int minValue = int.MaxValue;
int minValueIndex = -1;
for (int i = 0; i < list.Count; i++)
{
if (this.Columns[list[i]].DisplayIndex < minValue)
{
minValue = this.Columns[list[i]].DisplayIndex;
minValueIndex = i;
}
}
if (minValueIndex < 0)
{
return;
}
int dataGridViewInnerColumnIndex = list[minValueIndex];
columnIndexList.Add(dataGridViewInnerColumnIndex);
list.RemoveAt(minValueIndex);
}
}
protected object ConvertValue(string value)
{
if (string.IsNullOrEmpty(value))
{
return DBNull.Value;
}
else
{
return value.Replace("\r\n", "\n").Replace("\n", "\r\n");
}
}
#endregion
}
#endregion
#region DataGridView信息的保存和复原
public partial class dkDataGridView
{
#region 成员变量
private bool _isSaveDataGridViewData = false; // 需要保存数据标识
private bool _isSaveDataGridSetting = true; // DataGridView设定数据
private DataGridViewSettings _settings = null;
#endregion
#region 属性
///
/// 设定或者获取DataGridView设定数据(列的顺序·宽度)保存的标识
///
[System.ComponentModel.Browsable(true)]
[System.ComponentModel.DefaultValue(true)]
[System.ComponentModel.Description("设定或者获取DataGridView设定数据(列的顺序·宽度)保存的标识")]
public bool IsSaveDataGridViewSetting
{
get
{
return _isSaveDataGridSetting;
}
set
{
_isSaveDataGridSetting = value;
}
}
[System.ComponentModel.Browsable(true)]
[System.ComponentModel.DefaultValue(false)]
[System.ComponentModel.Description("设定或者获取DataGridView数据保存的标识")]
public bool IsSaveDataGridViewData
{
get
{
return _isSaveDataGridViewData;
}
set
{
_isSaveDataGridViewData = value;
}
}
private DataGridViewSettings DataGridViewSettings
{
get
{
if (_settings == null)
{
_settings = new DataGridViewSettings();
System.Text.StringBuilder sbKey = new System.Text.StringBuilder();
Control control = this;
while (control != null)
{
sbKey.Append("_");
sbKey.Append(control.Name);
control = control.Parent;
}
_settings.SettingsKey = sbKey.ToString();
}
return _settings;
}
}
#endregion
#region 方法或者函数
public void SaveDataGridViewData()
{
if (!IsSaveDataGridViewData)
{
return;
}
this.DataGridViewSettings.DataGridViewColumnInfos = GetDataGridViewColumnInfos();
this.DataGridViewSettings.Save();
}
public void RestoreDataGridViewData()
{
if (!IsSaveDataGridViewData)
{
return;
}
DataGridViewColumnInfo[] infos = this.DataGridViewSettings.DataGridViewColumnInfos;
if (infos == null || infos.Length == 0)
{
return;
}
for (int i = 0; i < infos.Length; i++)
{
DataGridViewColumnInfo info = infos[i];
string strColumnName = info.ColumnName;
if (this.Columns.Contains(strColumnName))
{
if (this.Columns[strColumnName].DisplayIndex != i)
{
this.Columns[strColumnName].DisplayIndex = i;
}
this.Columns[strColumnName].Width = info.Width;
}
}
}
private DataGridViewColumnInfo[] GetDataGridViewColumnInfos()
{
List list = new List();
for (int i = 0; i < this.Columns.Count; i++)
{
foreach (DataGridViewColumn column in this.Columns)
{
if (column.DisplayIndex == i && column.Visible)
{
DataGridViewColumnInfo info = new DataGridViewColumnInfo();
info.ColumnName = column.Name;
info.ColumnText = column.HeaderText;
info.TreeColumnText = GetTreeColumnText(column);
info.Width = column.Width;
info.Visible = column.Visible;
info.DataPropertyName = column.DataPropertyName;
info.DefaultCellStyle = column.DefaultCellStyle;
info.Frozen = column.Frozen;
list.Add(info);
break;
}
}
}
return list.ToArray();
}
private string GetTreeColumnText(DataGridViewColumn column)
{
if (this.ColumnTreeViewNode != null)
{
object[] colList = ColumnList.ToArray();
TreeNode tn = (TreeNode)colList[column.Index];
System.Text.StringBuilder sb = new System.Text.StringBuilder();
while (tn != null)
{
if (sb.Length > 0)
{
sb.Insert(0, tn.Name + "→");
}
else
{
sb.Append(column.HeaderText);
}
tn = tn.Parent;
}
return sb.ToString();
}
return column.HeaderText;
}
#endregion
}
#region DataGridView的列信息
[Serializable]
internal sealed class DataGridViewColumnInfo
{
public string ColumnName
{
get;
set;
}
public string DataPropertyName
{
get;
set;
}
public string ColumnText
{
get;
set;
}
public string TreeColumnText
{
get;
set;
}
public int Width
{
get;
set;
}
public bool Visible
{
get;
set;
}
public DataGridViewCellStyle DefaultCellStyle
{
get;
set;
}
public bool Frozen
{
get;
set;
}
}
#endregion
#region DataGridView信息保存类
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute(
"Dongke.IBOSS.Framework.Controls.dkDataGridView", "0.0.0.0")]
internal sealed class DataGridViewSettings :
global::System.Configuration.ApplicationSettingsBase
{
private static DataGridViewSettings _defaultInstance = ((DataGridViewSettings)(
global::System.Configuration.ApplicationSettingsBase.Synchronized(
new DataGridViewSettings())));
public static DataGridViewSettings Default
{
get
{
return _defaultInstance;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute(null)]
[global::System.Configuration.SettingsSerializeAs(
System.Configuration.SettingsSerializeAs.Binary)]
public DataGridViewColumnInfo[] DataGridViewColumnInfos
{
get
{
return (DataGridViewColumnInfo[])this["DataGridViewColumnInfos"];
}
set
{
this["DataGridViewColumnInfos"] = value;
}
}
}
#endregion
#endregion
#region 过滤处理
public partial class dkDataGridView
{
#region 公开方法/函数
public void FilterRow(FilterType filterType)
{
try
{
if (this.CurrentCell == null)
{
return;
}
FilterRow(this.CurrentCell.ColumnIndex, filterType, this.CurrentCell.Value);
}
catch (Exception ex)
{
throw ex;
}
}
public void FilterRow(int columnIndex, FilterType filterType, object value)
{
try
{
// DataTable不存在的情况,返回
if (this.CurrentDataTable == null || this.CurrentDataTable.Rows.Count < 1)
{
return;
}
DataGridViewColumn column = this.Columns[columnIndex];
if (column == null)
{
return;
}
if (string.IsNullOrEmpty(column.DataPropertyName))
{
return;
}
if (!(this.DataSource is DataView))
{
this.CurrentDataTable.DefaultView.AllowDelete = this.AllowUserToDeleteRows;
this.CurrentDataTable.DefaultView.AllowEdit = this.AllowUserToModifyRows;
this.CurrentDataTable.DefaultView.AllowNew = this.AllowUserToAddRows;
//this.DataSource = this.CurrentDataTable.DefaultView.ToTable();
this.DataMember = string.Empty;
}
string strValueString = value as string;
if (!string.IsNullOrEmpty(strValueString))
{
if (2 < strValueString.Length)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(strValueString, "^.[^\\%]*.$"))
{
MessageBox.Show(ControlsTips.DK_DataGridView_LikeError);
return;
}
}
}
bool isNumber = false;
string filter = string.Empty;
if (!string.IsNullOrEmpty(strValueString))
{
if (("Decimal".Equals(column.ValueType.Name)
|| "Int".Equals(column.ValueType.Name)
|| "Double".Equals(column.ValueType.Name)))
{
if (strValueString.StartsWith(">")
|| strValueString.StartsWith("<")
|| strValueString.StartsWith("="))
{
string tempValue = strValueString.Substring(1);
decimal tmpValueDec = 0;
bool flag = decimal.TryParse(tempValue, out tmpValueDec);
if (flag)
{
isNumber = true;
filter = column.DataPropertyName + strValueString;
}
}
else
{
if (strValueString.IndexOf("-") > 0)
{
string[] values = strValueString.Split('-');
decimal minValue = 0;
decimal maxValue = 0;
bool flag1 = decimal.TryParse(values[0], out minValue);
bool flag2 = decimal.TryParse(values[1], out maxValue);
if (flag1 && flag2)
{
isNumber = true;
filter = column.DataPropertyName + " > " + minValue + " AND " + column.DataPropertyName + " < " + maxValue;
}
}
}
}
}
if (!isNumber)
{
bool isHavedata = false;
if (!string.IsNullOrEmpty(strValueString)
&& (strValueString.IndexOf(",") >= 0 || strValueString.IndexOf(",") >= 0))
{
string[] values = strValueString.Split(new char[] { ',', ',' });
if (("Decimal".Equals(column.ValueType.Name)
|| "Int".Equals(column.ValueType.Name)
|| "Double".Equals(column.ValueType.Name)))
{
decimal tmpValue = 0;
for (int i = 0; i < values.Length; i++)
{
bool flag = decimal.TryParse(values[i], out tmpValue);
if (flag)
{
isHavedata = true;
filter += column.DataPropertyName + " = " + tmpValue + " OR ";
}
}
if (isHavedata)
{
filter = filter.Substring(0, filter.Length - 4);
}
}
else
{
isHavedata = true;
for (int i = 0; i < values.Length; i++)
{
filter += column.DataPropertyName + " = '" + values[i] + "' OR ";
}
filter = filter.Substring(0, filter.Length - 4);
}
}
if (!isHavedata)
{
string format;
if (Utility.IsNull(value))
{
format = "CONVERT([{0}], 'System.String') {1}";
}
else
{
format = "ISNULL(CONVERT([{0}], 'System.String'), '') {1}";
}
filter = string.Format(format, column.DataPropertyName.Replace("]", "]]"),
GetOperatorValue(filterType, value, null));
if (!string.IsNullOrEmpty(this.CurrentDataTable.DefaultView.RowFilter))
{
filter += string.Format(" AND {0}",
this.CurrentDataTable.DefaultView.RowFilter);
}
}
}
if (this.CurrentCell != null)
{
this.CurrentCell = this.Rows[0].Cells[columnIndex];
}
this.CurrentDataTable.DefaultView.RowFilter = filter;
if (_isOpenTotalRow)
{
// 重新计算合计行
dt = this.CurrentDataTable.DefaultView.ToTable();
CountTotalRow();
}
}
catch (Exception ex)
{
throw ex;
}
}
public void ResetFilter()
{
try
{
if (this.CurrentDataTable == null)
{
return;
}
if (this.CurrentCell != null)
{
this.CurrentCell = this.Rows[0].Cells[this.CurrentCell.ColumnIndex];
}
if (_isChildDGV && !string.IsNullOrEmpty(_viewRowFilterString))
{
this.CurrentDataTable.DefaultView.RowFilter = _viewRowFilterString;
}
else
{
this.CurrentDataTable.DefaultView.RowFilter = string.Empty;
}
if (_isOpenTotalRow)
{
// 重新计算合计行
dt = this.CurrentDataTable.DefaultView.ToTable();
CountTotalRow();
}
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region 受保护的方法/函数
protected string GetOperatorValue(FilterType filterType, object value, Type columnType)
{
if (Utility.IsNull(value))
{
switch (filterType)
{
case FilterType.NotEqual:
case FilterType.NotLike:
return "IS NOT NULL";
case FilterType.Equal:
case FilterType.Like:
default:
return "IS NULL";
}
}
else
{
string ope = "=";
switch (filterType)
{
case FilterType.NotEqual:
ope = "<>";
break;
case FilterType.Like:
ope = "LIKE";
value = ConvertRegularExpressionFilter(value + "");
break;
case FilterType.NotLike:
ope = "NOT LIKE";
value = ConvertRegularExpressionFilter(value + "");
break;
case FilterType.Equal:
default:
ope = "=";
break;
}
return string.Format("{0} '{1}'", ope, value);
}
}
#endregion
}
#endregion
#region 右键菜单处理
#region 右键菜单(过滤功能)
public class ToolStripRefine : ToolStripControlHost
{
#region 构造函数
public ToolStripRefine()
: base(new RefineControl())
{
}
#endregion
#region 公开方法/函数
public new string Text
{
get
{
return RefineControlInstance.TextBox.Text;
}
}
#endregion
#region 受保护方法/函数
RefineControl RefineControlInstance
{
get
{
return (RefineControl)Control;
}
}
#endregion
#region 委托
public event EventHandler RefineTextFixed;
#endregion
#region 重写方法
protected override void OnSubscribeControlEvents(Control c)
{
base.OnSubscribeControlEvents(c);
RefineControlInstance.TextBox.KeyDown += new KeyEventHandler(RefineControl_KeyDown);
}
protected override void OnUnsubscribeControlEvents(Control c)
{
base.OnUnsubscribeControlEvents(c);
RefineControlInstance.TextBox.KeyDown -= new KeyEventHandler(RefineControl_KeyDown);
}
#endregion
#region 事件
private void RefineControl_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
if (RefineTextFixed != null)
{
RefineTextFixed(this, e);
}
}
}
#endregion
}
#endregion
#region 过滤控件
class RefineControl : Control
{
#region 成员变量
private Label lblRefine = new Label();
private TextBox txtRefine = new TextBox();
#endregion
#region 属性
public TextBox TextBox
{
get
{
return txtRefine;
}
}
#endregion
#region 构造函数
public RefineControl()
{
// lblRefine
lblRefine.AutoSize = true;
lblRefine.Location = new System.Drawing.Point(0, 5);
lblRefine.Name = "label1";
lblRefine.Size = new System.Drawing.Size(40, 12);
lblRefine.TabIndex = 1;
lblRefine.Text = ControlsTips.DK_DataGridView_Refine;
// txtRefine
txtRefine.Location = new System.Drawing.Point(62, 2);
txtRefine.Name = "textBox1";
txtRefine.Size = new System.Drawing.Size(100, 19);
txtRefine.TabIndex = 2;
txtRefine.PreviewKeyDown += new PreviewKeyDownEventHandler(txtRefine_PreviewKeyDown);
// RefineControl
this.Height = 23;
this.Width = 144;
this.Controls.Add(lblRefine);
this.Controls.Add(txtRefine);
}
#endregion
#region 事件
private void txtRefine_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
if (e.Alt)
{
e.IsInputKey = true;
}
}
#endregion
}
#endregion
#endregion
#region CSV转换事件的参数类
public class CsvConvertingEventArgs : EventArgs
{
#region 成员变量
private int _columnIndex;
private object _value;
#endregion
#region 属性
public int ColumnIndex
{
get
{
return _columnIndex;
}
set
{
_columnIndex = value;
}
}
public object Value
{
get
{
return _value;
}
set
{
_value = value;
}
}
#endregion
#region 构造函数
public CsvConvertingEventArgs(int columnIndex, object value)
{
this.ColumnIndex = columnIndex;
this.Value = value;
}
#endregion
}
#endregion
}