LuckyLuke82 LuckyLuke82 - 4 months ago 26
Vb.net Question

Set Cursor in datagridview rows only

I want to have a "Help" cursor in DataGridView, but only from 1st row to end of rows, excluding column header. The code I currently use shows the help cursor everywhere over datagridview control - on column headers and even blank space under rows because I have docked datagridview in panel. It's probably simple, but how can I fix this? I have code to set cursor back to default when leaving DataGridView too.

Private Sub DataGridView1_CellMouseMove(sender As Object, e As DataGridViewCellMouseEventArgs) Handles DataGridView1.CellMouseMove
Dim dgv As DataGridView = DataGridView1
For r As Integer = 1 To dgv.RowCount - 1
Me.Cursor = Cursors.Help
Next
End Sub

Private Sub DataGridView1_CellMouseLeave(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellMouseLeave
Me.Cursor = Cursors.Default
End Sub

Answer

This will change the cursor to help only when over the cells. It excludes the title row as well as the left column, as well as the background. You can change the condition to exactly suit your needs

Private Sub DataGridView1_MouseMove(sender As Object, e As MouseEventArgs) Handles DataGridView1.MouseMove
    Dim myHitTest = DataGridView1.HitTest(e.X, e.Y)
    If myHitTest.RowIndex >= 0 AndAlso myHitTest.ColumnIndex >= 0 Then
        Me.Cursor = Cursors.Help
    Else
        Me.Cursor = Cursors.Default
    End If
End Sub