.NET Framework - Datagridview Determine if right click is on selected cells

Asked By Bill Schanks on 11-Feb-10 12:19 PM
VB 2005

How do I tell if a right click on a datagridview is in the selected
cells? I want to selected the cell if it is not, and if it is in the
selected cell range do nothing.

I have this code to select the right clicked cell, but how do I check
if it is in the selected cell range?

Private Sub DataGridView_CellMouseDown(ByVal sender As System.Object,
_
ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) _
Handles DataGridView.CellMouseDown

If e.Button = Windows.Forms.MouseButtons.Right Then
Me.DataGridView.CurrentCell =
Me.DataGridView.Rows(e.RowIndex).Cells(e.ColumnIndex)
End If

End Sub




Rich P replied to Bill Schanks on 11-Feb-10 02:01 PM
you can try something like this:

Dim SelectedCells As DataGridViewSelectedCellCollection =
datagridview1.SelectedCells

For Each cel As DatagridviewCell in SelectedCells
Debug.Print cel.ColumnIndex.ToString & " " cel.RowIndex.ToString
Next

Rich

*** Sent via Developersdex http://www.developersdex.com ***
Bill Schanks replied to Rich P on 11-Feb-10 04:29 PM
Thanks, got this work with reasonable performance:

If e.Button =3D Windows.Forms.MouseButtons.Right Then
Dim SelectedCells As DataGridViewSelectedCellCollection =3D
Me.DataGridView.SelectedCells
Dim bInselection As Boolean =3D False

'Check to see if click in selected range.. if it is do nothing
For Each cel As DataGridViewCell In SelectedCells
If e.ColumnIndex >=3D cel.ColumnIndex AndAlso _
e.ColumnIndex <=3D cel.ColumnIndex AndAlso _
e.RowIndex >=3D cel.RowIndex AndAlso _
e.RowIndex <=3D cel.RowIndex Then

bInselection =3D True
Exit For
End If
Next

'Select the cell, if it is not in the current selected range
If Not bInselection Then _
Me.DataGridView.CurrentCell =3D
Me.DataGridView.Rows(e.RowIndex).Cells(e.ColumnIndex)

End If
Bill Schanks replied to Bill Schanks on 11-Feb-10 04:51 PM
=3D
thing
Also _
Also _
ge

For those interested I found a much cleaner approach:

Private Sub DataGridView_CellMouseDown(ByVal sender As System.Object,
_
ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) _
Handles DataGridView.CellMouseDown

If e.Button =3D Windows.Forms.MouseButtons.Right AndAlso _
Not
Me.DataGridView.SelectedCells.Contains(Me.DataGridView.Rows(e.RowIndex).Cel=
ls(e.ColumnIndex))
Then _
Me.DataGridView.CurrentCell =3D
Me.DataGridView.Rows(e.RowIndex).Cells(e.ColumnIndex)

End Sub