I need to select a row in dataGridView with right click before ContextMenu shown because contextMenu is row-dependendt.
I've tried this:
if (e.Button == MouseButtons.Right)
{
var hti = dataGrid.HitTest(e.X, e.Y);
dataGrid.ClearSelection();
dataGrid.Rows[hti.RowIndex].Selected = true;
}
or:
private void dataGrid_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
dataGrid.Rows[e.RowIndex].Selected = true;
dataGrid.Focus();
}
}
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..
Best Answer
Try setting the current cell like this (this will set the
CurrentRow
property of theDataGridView
before the context menu item is selected):