Search code examples
vb.netcursordatagridviewcolumn

Changing cursor to "I-beam" when mousing over a read-only column in datagridview


I'm using Visual Basic 2012 and I'm working with a datagridview populated by an excel 2010 macro workbook. Some of the columns within my datagridview are read-only columns and I would like the cursor to change from the default cursor to an I-beam when the cursor moves into one of the two columns. As my code sits right now, I have an if-then statement in the mouse_enter event and mouse_leave event if the column is read-only. I'm having trouble understanding why the cursor isn't changing when I implement this code. If anyone has any suggestions on how to improve my code I would greatly appreciate it.

Private Sub DataGridView1_MouseHover(sender As Object, e As EventArgs) Handles DataGridView1.MouseHover
    If DataGridView1.CurrentCell.ReadOnly = True Then
        Cursor.Current = Cursors.IBeam
    Else
        Cursor.Current = Cursors.Default
    End If
End Sub

Private Sub DataGridView1_MouseLeave(sender As Object, e As EventArgs) Handles DataGridView1.MouseLeave
    Cursor.Current = Cursors.Default
End Sub

Solution

  • Try it in CellMouseMove Event ..

    Private Sub DataGridView1_CellMouseMove(sender As Object, e As EventArgs) Handles DataGridView1.CellMouseMove
    
        Dim x as Integer = e.ColumnIndex
    
        If DataGridView1.Columns(x).ReadOnly Then
            Cursor.Current = Cursors.IBeam
        Else
            Cursor.Current = Cursors.Default
        End If
    End Sub