views:

7364

answers:

6

How do you select a datagridview row on a right-click?

+7  A: 
    // Clear all the previously selected rows
    foreach (DataGridViewRow row in yourDataGridView.Rows)
    {
      row.Selected = false;
    }

    // Get the selected Row
    DataGridView.HitTestInfo info = yourDataGridView.HitTest( e.X, e.Y );

    // Set as selected
    yourDataGridView.Rows[info.RowIndex].Selected = true;
this gets really slow when the amount of rows is high...
m_oLogin
If your DataGridView has MultiSelect set to false then clearing the previous selection is unnecessary. Also, HitTestInfo can return HitTestInfo.Nowhere if the hit is not a valid Row/Column.
Stuart Dunkeld
+2  A: 
balexandre
+1  A: 

You can use JvR's code in the MouseDown event of your DataGridView.

Johann Blais
A: 

Subclass the DataGridView and create a MouseDown event for the grid,


private void SubClassedGridView_MouseDown(object sender, MouseEventArgs e)
{
    // Sets is so the right-mousedown will select a cell
    DataGridView.HitTestInfo hti = this.HitTest(e.X, e.Y);
    // Clear all the previously selected rows
    this.ClearSelection();

    // Set as selected
    this.Rows[hti.RowIndex].Selected = true;
}
Brendan
A: 

Make it behave similarly to the left mouse button? e.g.

private void dataGridView_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
    if (e.Button == MouseButtons.Right)
    {
        dataGridView.CurrentCell = dataGridView[e.ColumnIndex, e.RowIndex];
    }
}
Alan Christensen
A: 

You have to do two things:

  1. Clear all rows and Select the current. I loop through all rows and use the Bool Expression i = e.RowIndex for this

  2. If you have done Step 1 you still have a big pitfall:
    DataGridView1.CurrentRow does not return your previously selected row (which is quite dangerous). Since CurrentRow is Readonly you have to do

    Me.CurrentCell = Me.Item(e.ColumnIndex, e.RowIndex)

    Protected Overrides Sub OnCellMouseDown(
        ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs)
    
    
    
    MyBase.OnCellMouseDown(e)
    
    
    Select Case e.Button
        Case Windows.Forms.MouseButtons.Right
            If Me.Rows(e.RowIndex).Selected = False Then
                For i As Integer = 0 To Me.RowCount - 1
                    SetSelectedRowCore(i, i = e.RowIndex)
                Next
            End If
    
    
            Me.CurrentCell = Me.Item(e.ColumnIndex, e.RowIndex)
    End Select
    
    End Sub
SchlaWiener