development:net:grid_rc

DataGridView Select Row On Mouse Right Click (VB .NET)

Most people want to reduce the number of clicks when using a GUI application. When working with DataGridView, right click opens a context menu and keeps the selected row unchanged. So, you ether have to left click to select new row, then right click to open context menu and then select some option. Here is how you reduce this by one click:Create a sub for CellMouseDown event with the following code:

Private Sub DataGridView1_CellMouseDown(sender As Object, e As Windows.Forms.DataGridViewCellMouseEventArgs) Handles DataGridView1.CellMouseDown
    If e.Button = Windows.Forms.MouseButtons.Right Then
        If e.RowIndex < 0 Or e.ColumnIndex < 0 Then Exit Sub
        DataGridView1.CurrentCell = DataGridView1(e.ColumnIndex, e.RowIndex)
        ' Maybe modify the text on your context menu options here?
    End If
End Sub

Explanation:

  • Check if button is left of right
  • Check if click is outside the rows and columns
  • Set the selected row

This event fires before the MouseUp event of the grid (which displays the context menu)

You can also use this to modify the context menu options text depending on the selected row.

Enter your comment:
132 -2 = 
 
  • development/net/grid_rc.txt
  • Last modified: 2019/10/31 09:04
  • by 127.0.0.1