C# – Right click to select row in dataGridView

cdatagridviewright-clickrowselect

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 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();
        }
    }