话不多说,在DataGridView中的CurrentRow属性为只读,且其Index也不能动态设置,故只能在DataGridView中用左键来选择行,从而实现当前行的定位。
现在要实现在DataGridView中单击右键实现左键的功能,代码如下
Code
private void DetailDataGrid_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.Button == MouseButtons.Right && e.RowIndex > -1 && e.ColumnIndex > -1)
{
DetailDataGrid.CurrentRow.Selected = false;
DetailDataGrid.Rows[e.RowIndex].Selected = true;
//DetailDataGrid.CurrentCell = DetailDataGrid.Rows[e.RowIndex].Cells[e.ColumnIndex];
}
}
private void DetailDataGrid_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.Button == MouseButtons.Right && e.RowIndex > -1 && e.ColumnIndex > -1)
{
DetailDataGrid.CurrentRow.Selected = false;
DetailDataGrid.Rows[e.RowIndex].Selected = true;
//DetailDataGrid.CurrentCell = DetailDataGrid.Rows[e.RowIndex].Cells[e.ColumnIndex];
}
}
DatagridView的CellMouseDown事件添加如上代码,在不考虑注释代码的情况下,可以实现对当前选中行的不显示选中,而对鼠标右击的行实现选中
这样存在一个问题,CurrentRow的属性仍然为之前的哪个值,即使将鼠标右键选中的行的Selected设置为True也不能改变。
而在将注释代码注销后即可同时改变CurrentRow的属性,这样以后编码方便多了!
当然在对CurrentCell赋值的时候别忘了判断鼠标右击到DataGridView边框行列的情况
声明:本人是菜鸟,请高手们有什么好的意见建议尽管提,就是别扔砖头,首次发表文章,给点信心!