今天工作中遇到个关于Winform DataGrid的问题,记录之
我有一个DataGrid,帮定数据源后显示如下
用鼠标点击上图红圈处,会出现下图的情况:
出现最后两行都被选中,非常之郁闷
解决方法:
新建一个类,继承自DataGrid,并重写OnMouseDown方法,具体代码如下:
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WinFormStudy
{
public class MyDataGrid:System.Windows.Forms.DataGrid
{
public MyDataGrid()
{
}
private void UnSelectAll()
{
for(int i=0;i<this.ListManager.List.Count;i++)
{
this.UnSelect(i);
}
}
protected override void OnMouseDown(System.Windows.Forms.MouseEventArgs e)
{
System.Drawing.Point pt = new Point(e.X, e.Y);
DataGrid.HitTestInfo hti = this.HitTest(pt);
if(hti.Row>=0)
{
if(e.Button == MouseButtons.Left)
{
this.UnSelectAll();
this.CurrentRowIndex = hti.Row;
}
this.Select(hti.Row);
}
//base.OnMouseDown(e); //就是这个搞得鬼!!!
}
}
}
using System.Drawing;
using System.Windows.Forms;
namespace WinFormStudy
{
public class MyDataGrid:System.Windows.Forms.DataGrid
{
public MyDataGrid()
{
}
private void UnSelectAll()
{
for(int i=0;i<this.ListManager.List.Count;i++)
{
this.UnSelect(i);
}
}
protected override void OnMouseDown(System.Windows.Forms.MouseEventArgs e)
{
System.Drawing.Point pt = new Point(e.X, e.Y);
DataGrid.HitTestInfo hti = this.HitTest(pt);
if(hti.Row>=0)
{
if(e.Button == MouseButtons.Left)
{
this.UnSelectAll();
this.CurrentRowIndex = hti.Row;
}
this.Select(hti.Row);
}
//base.OnMouseDown(e); //就是这个搞得鬼!!!
}
}
}