By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,281 Members | 2,216 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,281 IT Pros & Developers. It's quick & easy.

DataGridView: Force row selection on right-click?

P: n/a
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
Nov 23 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
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.DataGridViewCellMouseEventArg s 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.DataGridViewCellMouseEventArg s)_
Handles DataGridView1.CellMouseClick

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

Nov 23 '05 #2

P: n/a
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
"Spencer Williamson" <ve******@nospamhotmail.com> wrote in message
news:%2****************@TK2MSFTNGP15.phx.gbl...
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.DataGridViewCellMouseEventArg s 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.DataGridViewCellMouseEventArg s)_
Handles DataGridView1.CellMouseClick

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

Nov 23 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.