110,536
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Windows.Forms;
namespace CommonTools.Control
{
[ToolboxItem(true), Category("ZteCommonTools"), Description("ZteCommonTools")]
public class XDataGridView : DataGridView
{
private XDataGridViewType xType;
[Browsable(true), Category("ZteCommonTools"), Description("DataGridView类型."), DefaultValue(XDataGridViewType.None)]
public XDataGridViewType XType
{
get { return this.xType; }
set { this.xType = value; }
}
private Boolean xRightMouseButtonSelect;
[Browsable(true), Category("ZteCommonTools"), Description("允许鼠标右键选择DataGridViewRow."), DefaultValue(false)]
public Boolean XRightMouseButtonSelect
{
get { return this.xRightMouseButtonSelect; }
set { this.xRightMouseButtonSelect = value; }
}
protected override void OnCellMouseDown(DataGridViewCellMouseEventArgs e)
{
Boolean setAnchorCellAddress = false;
base.OnCellMouseDown(e);
if (!e.Button.Equals(MouseButtons.Right)) return; // 只处理鼠标右键.
if (e.RowIndex.Equals(-1) || e.ColumnIndex.Equals(-1)) return; // 不处理RowHeader或ColumnHeader上的响应事件.
if (!this.xRightMouseButtonSelect) return; // 只处理开启"右键选择"功能的响应事件.
switch (ModifierKeys)
{
case Keys.Control:
this.Rows[e.RowIndex].Cells[e.ColumnIndex].Selected = !this.Rows[e.RowIndex].Cells[e.ColumnIndex].Selected;
this.SetCurrentCellAddressCore(e.ColumnIndex, e.RowIndex, false, true, true);
break;
case Keys.Shift:
setAnchorCellAddress = true;
DataGridViewCell cell = this.CurrentCell;
this.ClearSelection();
if (cell.RowIndex < e.RowIndex)
{
for (int i = cell.RowIndex; i <= e.RowIndex; i++)
{
for (int j = cell.ColumnIndex; j <= e.ColumnIndex; j++)
{
this.Rows[i].Cells[j].Selected = true;
}
}
}
else
{
for (int i = e.RowIndex; i <= cell.RowIndex; i++)
{
for (int j = e.ColumnIndex; j <= cell.ColumnIndex; j++)
{
this.Rows[i].Cells[j].Selected = true;
}
}
}
break;
default:
this.ClearSelection();
this.Rows[e.RowIndex].Cells[e.ColumnIndex].Selected = !this.Rows[e.RowIndex].Cells[e.ColumnIndex].Selected;
this.SetCurrentCellAddressCore(e.ColumnIndex, e.RowIndex, false, true, true);
break;
}
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace CommonTools.Control
{
public enum XDataGridViewType
{
/// <summary>
/// 无特殊功能限制的DataGridViewType.
/// </summary>
None,
}
}
//写在CellMouseDown事件中
private void DataGridView_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.RowIndex >= 0)
{
if (e.Button == System.Windows.Forms.MouseButtons.Right)
{
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Selected = true;
dataGridView1.ClearSelection();
}
}
if (e.Button == MouseButtons.Right)
{
if (e.RowIndex == -1) return;
sGrid.Rows[e.RowIndex].Selected = true;
}