c# - 当鼠标在 datagridview 行中时显示每个项目的工具提示

标签 c# .net winforms datagridview tooltip

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

我的表 product 包含以下列:

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

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

product name 
product price 
product image ....

现在我想像这样显示工具提示:如果我将鼠标悬停在产品图片上,将显示该产品的产品描述。我想对每一行都这样做。有人可以帮忙解决这个问题吗?

最佳答案

看看 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。但是还有其他选择。

关于c# - 当鼠标在 datagridview 行中时显示每个项目的工具提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7173430/

相关文章:

c# - 如何使用c#检查激活了哪些Windows功能

winforms - Datagridview,禁用按钮/行

c# - 关于 IsNullOrWhiteSpace() 的快速提示中的 "String"与 "string"

.net - Bitbucket 管道 .NET Core 测试输出

c# - OWIN SignOut 不会删除 cookie

c++ - 如何关闭 SYSTEM_HANDLE(或另一个进程中打开的文件句柄)

.net - 无法订阅 DelegateCommand.CanExecuteChanged

c# - 在面板上绘制文本

C# WinRT 类型类缺少函数

c# - 将 Clarion 过程声明转换为 C# DLLImport