如何在鼠标悬停时更改DataGridView单元格图像? [英] How to change DataGridView cell image on mouseover?

查看:100
本文介绍了如何在鼠标悬停时更改DataGridView单元格图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在像这样在datagridviews列单元格中绘制图像:

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)?

推荐答案

首先,您的代码正在创建一个每个要显示该图像的单元格的新图像。每个单元实际上并不需要自己的个人图像对象。

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()

然后像FormLoad这样的私有ImgBalls:

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
                        }

然后使用它 like 悬停(不延迟):

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:

请注意,如果null值无效,而不是图像无效,还可以使用 CellErrorText 提供红色的感叹号和一些文本。

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.

这篇关于如何在鼠标悬停时更改DataGridView单元格图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆