最近,我要实现“WINFORM中,能样实现按住Ctrl或shift,用鼠标点击DataGrid任何一行对DATAGRID多选”的功能 在网上找了找,找到个vb的方法:说是要重写用户控件。我把代码改成 c# 的类了 (修改后的代码如下,测试通过)!但是做到这步,我就不知道接下来,应该怎么把这个“MyDataGrid”运用到微软的datagrid控件上来了?希望大家尽力帮忙,尽量详细点!感激!!!!!!!!
public class MyDataGrid:DataGrid
{
private ArrayList m = new ArrayList(); public int[] MultiSelectedIndex
{
get { return (int[])m.ToArray(typeof(int)) ; }
}
public MyDataGrid()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
protected override void OnMouseDown(System.Windows.Forms.MouseEventArgs e)
{
Point posdg = new Point(e.X, e.Y);
DataGrid.HitTestInfo hitDG = HitTest(posdg);
if(HitDataGrid(hitDG))
{
base.OnMouseDown(e);
}
}
private bool HitDataGrid(DataGrid.HitTestInfo Hit)
{
switch( ModifierKeys )
{
case Keys.Control :
{
if (Hit.Row > -1)
{
if (m.IndexOf(Hit.Row) > -1)
{
m.Remove(Hit.Row) ;
UnSelect(Hit.Row) ;
}
else
{
m.Add(Hit.Row) ;
Select(Hit.Row) ;
}
}
return false ;
}
case Keys.Shift :
{
if (Hit.Row > -1 )
{
foreach (int IndexOld in m )
{
UnSelect(IndexOld) ;
}
m.Clear() ;
int i, intStep ;
if (Hit.Row > CurrentRowIndex )
{
intStep = 1 ;
}
else
{
intStep = -1 ;
}
for( i = CurrentRowIndex;i<= Hit.Row ; i=i+intStep )
{
m.Add(i) ;
Select(i) ;
}
}
return false ;
}
default :
{
foreach (int index in m)
{
UnSelect(index) ;
}
m.Clear() ;
if (Hit.Type == DataGrid.HitTestType.RowHeader)
{
m.Add(Hit.Row) ;
}
return true ;
}
}
public class MyDataGrid:DataGrid
{
private ArrayList m = new ArrayList(); public int[] MultiSelectedIndex
{
get { return (int[])m.ToArray(typeof(int)) ; }
}
public MyDataGrid()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
protected override void OnMouseDown(System.Windows.Forms.MouseEventArgs e)
{
Point posdg = new Point(e.X, e.Y);
DataGrid.HitTestInfo hitDG = HitTest(posdg);
if(HitDataGrid(hitDG))
{
base.OnMouseDown(e);
}
}
private bool HitDataGrid(DataGrid.HitTestInfo Hit)
{
switch( ModifierKeys )
{
case Keys.Control :
{
if (Hit.Row > -1)
{
if (m.IndexOf(Hit.Row) > -1)
{
m.Remove(Hit.Row) ;
UnSelect(Hit.Row) ;
}
else
{
m.Add(Hit.Row) ;
Select(Hit.Row) ;
}
}
return false ;
}
case Keys.Shift :
{
if (Hit.Row > -1 )
{
foreach (int IndexOld in m )
{
UnSelect(IndexOld) ;
}
m.Clear() ;
int i, intStep ;
if (Hit.Row > CurrentRowIndex )
{
intStep = 1 ;
}
else
{
intStep = -1 ;
}
for( i = CurrentRowIndex;i<= Hit.Row ; i=i+intStep )
{
m.Add(i) ;
Select(i) ;
}
}
return false ;
}
default :
{
foreach (int index in m)
{
UnSelect(index) ;
}
m.Clear() ;
if (Hit.Type == DataGrid.HitTestType.RowHeader)
{
m.Add(Hit.Row) ;
}
return true ;
}
}
楼主要实现什么功能?组合键?
MyDataGrid 是我已经写好的用户控件类
把你的代码生成DLL
然后引用一下
第二种方法是:
还是直接拖MS DataGrid到你的窗口,
切换到代码中把MS的dataGrid命名及类改为你自己的即可 例如
private System.Windows.Forms.DataGrid dataGrid1;
改成
private MyDataGrid dataGrid1; 或者替换System.Windows.Forms.DataGrid为MyDataGrid 即搞定
樓主犯了象我以前一樣的問題.
flygoldfish(长江支流) 說的很詳細了﹐我不再多說廢話.