在vs 2003中,难免会使用DataGrid,DataGrid本身的currentRowIndex属性会给我们带来一个麻烦,就是currentRowIndex默认值为0,从0开始索引
有人不禁会问,这会带来什么影响呢,影响就是,如果你利用currentRowIndex来定位选中的哪行数据,这个时候,你就会发现,如此棘手
比如你选择的数据如下:
this.dataGrid1.select(dataGrid1.currentRowIndex)
然后比如该行第一列的值为ID,主键
int id = (DataGrid1.currentRowIndex,0)
这个时候如果你没在DataGrid中选择任何行,那么默认取得的id为第一行的数据
如何避免呢?看下面代码...
/// <summary>
/// 利用此事件来获取鼠标点击在dataGrid的什么地方,来控制选中了哪行
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void dataGrid1_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
{
System.Drawing.Point pt = new Point(e.X,e.Y);
System.Windows.Forms.DataGrid.HitTestInfo hti = this.dataGrid1.HitTest(pt);
if(hti.Type == DataGrid.HitTestType.Cell || hti.Type == DataGrid.HitTestType.RowHeader)
{
IsSelectedRow = true;
this.dataGrid1.Select(dataGrid1.CurrentRowIndex);
}
else
{
IsSelectedRow = false;
}
}
这个时候,就可以利用此事件,来判断是否真正的选中了某行!