用鼠标右键选择DataGridView单元格或行

时间:2022-06-30 21:46:05

  在datagirdview_cellmousedown事件中先将CurrentCell(或CurrentRow)的Selected属性设为false,然后将鼠标右键点击的单元格(或行)设为CurrentCell(或CurrentRow),最后再将CurrentCell(或CurrentRow)的Selected属性设为true。

  参考代码如下:

//右键可选中单元格
private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.Button == MouseButtons.Right && e.Clicks == )
{
dataGridView1.CurrentCell.Selected = false;
dataGridView1.CurrentCell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
dataGridView1.CurrentCell.Selected = true;
}
}