博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

datagridview右键选中单元格并获取到焦点

Posted on 2012-11-09 16:25  JmrBrvae  阅读(915)  评论(0编辑  收藏  举报

有个项目,需要在datagridview的单元格里加右键菜单,进行数据操作。

最开始用的代码是:

private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.RowIndex >=0) {
                if (e.Button == MouseButtons.Right) {
                    dataGridView1.ClearSelection();
                    dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Selected = true;
                  
                }
            }
        }

  这个是可以实现用右键选中单元格的效果,但是我发现,这个选择并没有获取到单元格的焦点,意思也就是说,你取currentCell的值,应该还是取的之前

用左键点击的单元格的值。

那么,用下面的代码,就可以实现右键选中单元格并获取到焦点。

private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.RowIndex >=0) {
                if (e.Button == MouseButtons.Right) {
                    dataGridView1.ClearSelection();
                    dataGridView1.CurrentCell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
                }
            }
        }

  在此记录一下,方便以后查阅。