右键单击以选择 dataGridView 中的行 [英] Right click to select row in dataGridView
本文介绍了右键单击以选择 dataGridView 中的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在显示 ContextMenu 之前右键单击 dataGridView 中的一行,因为 contextMenu 依赖于行.
I need to select a row in dataGridView with right click before ContextMenu shown because contextMenu is row-dependendt.
我已经试过了:
if (e.Button == MouseButtons.Right)
{
var hti = dataGrid.HitTest(e.X, e.Y);
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] 时,我只看到左键单击选择的行,而不是右键单击选择的行..
This works but when I try to read dataGrid.Rows[CurrentRow.Index] I see only the row selected with left click and not those selected with right click..
推荐答案
尝试像这样设置当前单元格(这将设置 DataGridView
之前的 CurrentRow
属性上下文菜单项被选中):
Try setting the current cell like this (this will set the CurrentRow
property of the DataGridView
before the context menu item is selected):
private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
var dataGrid = (DataGridView) sender;
if (e.Button == MouseButtons.Right && e.RowIndex != -1)
{
var row = dataGrid.Rows[e.RowIndex];
dataGrid.CurrentCell = row.Cells[e.ColumnIndex == -1 ? 1 : e.ColumnIndex];
row.Selected = true;
dataGrid.Focus();
}
}
这篇关于右键单击以选择 dataGridView 中的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文