DataGridView: Force row selection on right-click?

S

Spencer Williamson

Anyone know how to force the row to select when user right clicks the grid?
I have SelectionMode set to DataGridViewSelectionMode.FullRowSelect.


I tried this...

Private Sub DataGridView1_MouseDown(ByVal sender As Object, ByVal e As
System.Windows.Forms.MouseEventArgs) Handles DataGridView1.MouseDown
If e.Button = Windows.Forms.MouseButtons.Right Then
Dim mouseArg As New
System.Windows.Forms.MouseEventArgs(Windows.Forms.MouseButtons.Left, 1, e.X,
e.Y, 0)
DataGridView1_MouseDown(sender, mouseArg)
End If
End Sub

-Spencer
 
S

Spencer Williamson

Here's the answer:

With the DataGridView in VS 2005 there are two ways to do this.

The first is to use the DataGridView.HitTest to get the row index. Then
select the row using that index

The second and easier option is to use the DataGridView_CellMouseClick
event. The event passes a
System.Windows.Forms.DataGridViewCellMouseEventArgs that has the row index
attached. Here's the code I used:

Private Sub DataGridView1_CellMouseClick(ByVal sender As Object, ByVal e
As _
System.Windows.Forms.DataGridViewCellMouseEventArgs)_
Handles DataGridView1.CellMouseClick

If e.Button = Windows.Forms.MouseButtons.Right Then
DataGridView1.Rows(e.RowIndex).Selected = True
End If
End Sub
 
G

Greg Burns

I would change this:
If e.Button = Windows.Forms.MouseButtons.Right Then

to:
If e.Button = Windows.Forms.MouseButtons.Right AndAlso e.RowIndex >= 0 Then

or you'll get an error if right-clicking on the header.

Greg
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top