右键单击以选择dataGridView中的行
我需要在显示ContextMenu之前右键单击dataGridView中的一行,因为contextMenu是row-dependendt。
我试过这个:
if (e.Button == MouseButtons.Right) { var hti = dataGrid.HitTest(eX, eY); dataGrid.ClearSelection(); dataGrid.Rows[hti.RowIndex].Selected = true; }
要么:
private void dataGrid_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e) { if (e.Button == MouseButtons.Right) { dataGrid.Rows[e.RowIndex].Selected = true; dataGrid.Focus(); } }
这有效,但当我尝试读取dataGrid.Rows [CurrentRow.Index]时,我只看到左键单击选中的行而不是右键单击选中的行。
尝试像这样设置当前单元格(这将在选择上下文菜单项之前设置DataGridView
的CurrentRow
属性):
private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e) { if (e.Button == MouseButtons.Right) { // Add this dataGrid.CurrentCell = dataGrid.Rows[e.RowIndex].Cells[e.ColumnIndex]; // Can leave these here - doesn't hurt dataGrid.Rows[e.RowIndex].Selected = true; dataGrid.Focus(); } }
我意识到这个线程已经老了,我只想添加一件事:如果你想在多行上选择并执行操作:你可以检查你是否已经选择了右键单击的行。 这样,DataGridview在这方面的行为就像一个ListView。 因此,右键单击尚未选择的行:选择此行并打开上下文菜单。 右键单击已选择的行只会为您提供上下文菜单,并按预期保留所选行。
private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e) { if (e.RowIndex != -1 && e.ColumnIndex != -1) { if (e.Button == MouseButtons.Right) { DataGridViewRow clickedRow = (sender as DataGridView).Rows[e.RowIndex]; if (!clickedRow.Selected) dataGridView1.CurrentCell = clickedRow.Cells[e.ColumnIndex]; var mousePosition = dataGridView1.PointToClient(Cursor.Position); ContextMenu1.Show(dataGridView1, mousePosition); } } }
private void grid_listele_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e) { if (e.Button == MouseButtons.Right) { grid_listele.ClearSelection(); grid_listele[e.ColumnIndex, e.RowIndex].Selected = true; } }
if (e.Button == System.Windows.Forms.MouseButtons.Right) { var hti = GridView.HitTest(eX, eY); GridView.ClearSelection(); int index = hti.RowIndex; if (index >= 0) { GridView.Rows[hti.RowIndex].Selected = true; LockFolder_ContextMenuStrip.Show(Cursor.Position); } }
这是我猜的准确方法