当鼠标位于数据网格中时,显示数据网格行中每个项目的工具提示

时间:2011-08-24 09:49:38

标签: c# .net winforms datagridview tooltip

当您将鼠标悬停在该特定行中的项目上时,如何为datagridview中的每个项目显示datagridview的工具提示?

我的表product包含列:

product name 
product price 
product description
product image ....

我要求我有一个datagridview列,我从数据库中获取这些:

product name 
product price 
product image ....

现在我想要显示如下工具提示:如果我将鼠标悬停在产品图片上,则会显示该产品的产品说明。我想为每一行做这件事。有人可以帮忙解决这个问题吗?

3 个答案:

答案 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.ColumnIndexDataGridViewCellEventArgs.RowIndex值,并使用{{设置相应单元格中的文本作为工具提示文本1}}。

如果效果很好。

这样的事情:

ToolTip.SetToolTip