当您将鼠标悬停在该特定行中的项目上时,如何为datagridview
中的每个项目显示datagridview
的工具提示?
我的表product
包含列:
product name
product price
product description
product image ....
我要求我有一个datagridview
列,我从数据库中获取这些:
product name
product price
product image ....
现在我想要显示如下工具提示:如果我将鼠标悬停在产品图片上,则会显示该产品的产品说明。我想为每一行做这件事。有人可以帮忙解决这个问题吗?
答案 0 :(得分:42)
查看DataGridViewCell.ToolTipText property并使用DataGridView的CellFormatting
事件来设置此属性值。您可以使用事件的DataGridViewCellFormattingEventArgs
ColumnIndex
属性来确定是否要为要为其设置工具提示的列触发事件,如果是,请使用事件RowIndex
指定该工具提示值。
我链接的MSDN文章中的示例有一个很好的使用示例,但您的代码可能如下所示:
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) {
if (e.ColumnIndex == dataGridView1.Columns[nameOrIndexOfYourImageColumn].Index) {
var cell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
// Set the Cell's ToolTipText. In this case we're retrieving the value stored in
// another cell in the same row (see my note below).
cell.ToolTipText = dataGridView1.Rows[e.RowIndex].Cells[nameOrIndexOfYourDescriptionColumn].Value.ToString();
}
}
其中:
nameOrIndexOfYourImageColumn
=图像列的列名称或索引值
nameOrIndexOfYourDescriptionColumn
=包含描述数据的列名称或索引值。
注意:您需要某种方法来检索行的描述数据。执行此操作的常用方法是在DataGridView中为其创建一个列,但是因为您不希望显示此列,所以将其Visible
属性设置为false。但是还有其他选择。
答案 1 :(得分:5)
填写datagridview
时,只需将单元格的TooltipText
属性设置为您要显示的文字。
答案 2 :(得分:4)
我通过存储要在每个Tag
属性的DataGridViewCell
属性中的每个单元格的工具提示中显示的文本来完成此操作。
然后在DataGridView.CellMouseEnter
事件中,您可以看到鼠标在哪个单元格中使用DataGridViewCellEventArgs.ColumnIndex
和DataGridViewCellEventArgs.RowIndex
值,并使用{{设置相应单元格中的文本作为工具提示文本1}}。
如果效果很好。
这样的事情:
ToolTip.SetToolTip