Moving focus when right-clicking on a datagridview

The .NET framework integrates a context menu that easily can be bound to any datagridview. By default, this context menu operates on the “selected row”. But what if you’re user right-clicks somewhere else on the grid ? He will still get an context menu that operates on the selected row, even tho it appears on a totally different row.

Needless to say, this can be quite confusing. By moving the focus of the grid on right-click, we can both show the user that his selection point has changed, and select the correct row for our operation.

To archive this, you can handle the CellMouseDown event, and detect the location the user clicked. Next, move the “current cell” of the grid to that location.Now the right-click will first move the focus of the data grid to the correct location, and then show the context menu.

private void DataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e) {
    if (e.ColumnIndex != -1 && e.RowIndex != -1 && e.Button == MouseButtons.Right) {
        var view = (DataGridView) sender;
        DataGridViewCell cell = view[e.ColumnIndex, e.RowIndex];
        cell.DataGridView.ClearSelection();
        view.CurrentCell = view[e.ColumnIndex, e.RowIndex];
    }
}