Mouse hover DataGridView

Hello,

I want to change the cursor type when the mouse goes over a certain column in a dataview. I've the following code:

Private Sub DataGridView1_MouseHover(ByVal sender As Object, ByVal e As System.EventArgs) Handles DataGridView1.MouseHover
If DataGridView1.CurrentCell.ColumnIndex = 7 Then
DataGridView1.Cursor = Cursors.Help
Else
DataGridView1.Cursor = Cursors.Default
End If
End Sub

The problem is that when entering the DataView, the cursors goes over the headers and I receive an error because there is no CurrentCell!
Can annyone help me please

Thanks,

Joao Pinto



Answer this question

Mouse hover DataGridView

  • Neotech

    I would use a datagridview HitTestInfo to see what cell the mouse is over. I dont think it is likely that the mouse is over the current cell. You should also set the cursor back to the default when you leave the datagridview.




    Private Sub DataGridView1_MouseHover(ByVal sender As Object, ByVal e As System.EventArgs) Handles DataGridView1.MouseHover
    Dim pt As New Point
    Dim hti As DataGridView.HitTestInfo
    Try
    pt = Me.PointToClient(MousePosition)
    Catch ex As Exception
    Return
    End Try
    hti = DataGridView1.HitTest(pt.X, pt.Y)
    If hti.Type = DataGridViewHitTestType.Cell AndAlso hti.ColumnIndex = 1 Then
    DataGridView1.Cursor = Cursors.Hand
    Else
    DataGridView1.Cursor = Cursors.Default
    End If
    End Sub
    Private Sub DataGridView1_MouseLeave(ByVal sender As Object, ByVal e As System.EventArgs) Handles DataGridView1.MouseLeave
    DataGridView1.Cursor = Cursors.Default
    End Sub




  • Nima_Don

    try using the Cursor class instead or rather check to see if there is a current cell before changing the cursor...better error handling. Example:

     

    if Me.DataGridView.CurrentCell <> DBNull.Value then

    'it *maybe* DBNull.Value but check to see if there is a value in the CurrentCell by stepping through the debugger and making sure the mouse/cursor hover overs the empty cell to see the value of CurrentCell

       if Me.DataGridView.CurrentCell.ColumnIndex = 7 then

          Me.DataGridView.Cursor = Cursors.Help

       else

          Me.DataGridView.Cursor = Cursors.Default

       end if

    end if



  • Mouse hover DataGridView