Zach Johnson Zach Johnson - 2 months ago 30
Vb.net Question

How to change DataGridView cell image on mouseover?

I am painting an image in a datagridviews columns cells like so:

Private Sub dataGridView1_CellPainting(sender As Object, e As DataGridViewCellPaintingEventArgs) Handles DataGridView1.CellPainting
If e.ColumnIndex = 20 AndAlso e.RowIndex >= 0 Then

If String.IsNullOrEmpty(e.Value.ToString) Then

e.Paint(e.CellBounds, DataGridViewPaintParts.All)
Dim img As Image = Image.FromFile("C:\Users\me\Desktop\glass.png")
e.Graphics.DrawImage(img, e.CellBounds.Left + 10, e.CellBounds.Top + 5, 25, 25)
e.Handled = True
End If

End If
End Sub


Is it possible to switch the image to another if I hover over one of the cells (just for the hovered cell not all cells)?

Answer

First thing, your code is creating a new image for each cell where that image is to be displayed. Each cell doesn't really need its own personal image object.

Also, rather than loading from disk (which means the file could be deleted or moved), you could add the image to resources. Getting it from there will still create a new image object each time, so store them in an array:

Private ImgBalls As Image()

Then somewhere like FormLoad:

' ToDo: add a BulletColor enum for indexing
ImgBalls = New Image() {
                        My.Resources.ballblack, My.Resources.ballblue,
                        My.Resources.ballgreen, My.Resources.ballorange,
                        My.Resources.ballred, My.Resources.ballpurple,
                        My.Resources.ballyellow
                        }

Then using it like a hover (no delay):

Private Sub dgv1_CellMouseEnter(etc etc etc...
    If e.RowIndex < 0 OrElse dgv1.Rows(e.RowIndex).IsNewRow Then Return

    If e.ColumnIndex = 5 Then
        dgv1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = ImgBalls(6)
    End If
End Sub

Private Sub dgv1_CellMouseLeave(etc etc etc...
    If e.RowIndex < 0 OrElse dgv1.Rows(e.RowIndex).IsNewRow Then Return

    If e.ColumnIndex = 5 Then
        dgv1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = ImgBalls(0)
    End If
End Sub

This changes a default black bullet to yellow when the mouse is over it:

enter image description here

Note that if a null value is invalid, rather than an image you can also use CellErrorText to provide a red exclamation and some text.