Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Right click to select row in dataGridView

I need to select a row in a DataGridView with right click before a ContextMenu is shown because the ContextMenu is row-dependent.

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.

like image 323
user2396911 Avatar asked May 27 '13 02:05

user2396911


2 Answers

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();
        }
    }
like image 172
Gjeltema Avatar answered Nov 16 '22 19:11

Gjeltema


I realize this thread is old, I just wanted to add one thing: If you want to be able to select, and perform the action, on multiple rows: you can check to see if the row you are right-clicking is already selected. This way the DataGridview behaves likes a ListView in this regard. So right clicking on a row not already selected: selects this row and open the context menu. Right clicking on a row already selected just gives you the context menu and keep the selected rows as expected.

 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);
            }
        }
    }
like image 3
David Wakeman Avatar answered Nov 16 '22 18:11

David Wakeman