Domanda

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
È stato utile?

Soluzione

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

Altri suggerimenti

Kratz is correct in that you need to use the cell that the mouse is over not the CurrentCell attribute of the DataGridView which isn't necessarily where the mouse is. Which will make this a lot more tricky.

So basically this means you need to calculate the lower and upper bounds of each column you want to change the cursor to an IBeam for. So say you have a datagridview with 3 columns and you want to use the IBeam for the second column. Your lower bounds will be the width of the first column and the upper bounds will be the width of the first column plus the width of the second.

So your code will look like:

Private Sub DataGridView1_MouseMove(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles DataGridView1.MouseMove
    If Not e.Location.IsEmpty Then
        Dim lowerBounds As Integer = DataGridView1.Columns("FirstColumnsName").Width
        Dim UpperBounds As Integer = DataGridView1.Columns("FirstColumnsName").Width + DataGridView1.Columns("SecondColumnsName").Width

        If e.X >= lowerBounds AndAlso e.X < UpperBounds Then
            Cursor.Current = Cursors.IBeam
        Else
            Cursor.Current = Cursors.Default
        End If
    End If
End Sub

If you have multiple columns to switch for then you will need to calculate the space that they cover and add them to your if statement individually. You will also still need the mouse leave event to reset the cursor.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top