新方法DataGridView通过鼠标右键选中行

private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
    if (e.Button == MouseButtons.Right)
        {
            if (e.RowIndex >= 0)
            {
                dataGridView1.ClearSelection();
                dataGridView1.Rows[e.RowIndex].Selected = true;
                dataGridView1.CurrentCell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
                contextMenuStrip1.Show(MousePosition.X, MousePosition.Y);
            }
        }
    }
}
在DataGridView中的CurrentRow属性为只读,且其Index也不能动态设置,故只能在DataGridView中用左键来选择行,从而实现当前行的定位。
现在要实现在DataGridView中单击右键实现左键的功能,代码如下:
private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
    if (e.Button == MouseButtons.Right && e.RowIndex > -1 && e.ColumnIndex > -1)
    {
        dataGridView1.CurrentRow.Selected = false;
        dataGridView1.Rows[e.RowIndex].Selected = true;
    }
}
DatagridView的CellMouseDown事件添加如上代码,在不考虑注释代码的情况下,可以实现对当前选中行的不显示选中,而对鼠标右击的行实现选中
这样存在一个问题,CurrentRow的属性仍然为之前的哪个值,即使将鼠标右键选中的行的Selected设置为True也不能改变。
而在将注释代码注销后即可同时改变CurrentRow的属性,这样以后编码方便多了!
当然在对CurrentCell赋值的时候别忘了判断鼠标右击到DataGridView边框行列的情况
以上本文来自CSDN博客:http://blog.csdn.net/Adi_liu/archive/2009/01/07/3725230.aspx

<===========================================>

由于本人要实现的是在dataGridView中通过右键所在位置是否为数据行,没有则禁用部份菜单项。
以上代码无法判断右键是否在空置,代码修改如下:

 1private void dataGridView1_MouseDown(object sender, MouseEventArgs e)
 2{
 3    DataGridView.HitTestInfo rows = this.dataGridView1.HitTest(e.X, e.Y);
 4    if (e.Button == MouseButtons.Right)
 5    {
 6        if (rows.RowIndex > -1)
 7        {
 8            this.dataGridView1.ClearSelection();
 9            this.dataGridView1.CurrentRow.Selected = false;
10            this.dataGridView1.Rows[rows.RowIndex].Selected = true;
11        }

12        else
13        {
14        }

15    }

16}

更多参考单击这里

posted @ 2009-11-12 17:02  雅凡网  阅读(1959)  评论(0编辑  收藏  举报