vb.net 显示 datagridviewcombobox 中每个项目的工具提示文本

vb.net show tooltiptext for every item in datagridviewcombobox

我搜索了显示 datagridview 的工具提示文本,但我只获得了 datagridviewcell 的工具提示文本。我想要的是在从 datagridviewcomboboxcolumn 的下拉列表中突出显示(鼠标悬停)项目时显示的工具提示文本。 我在组合框列的数据绑定中设置了工具提示文本,但它在运行时不显示任何内容。

'assuming dtExpense is the datatable used as datasource
With CType(DataGridView3.Columns(2), DataGridViewComboBoxColumn)
    .AutoComplete = True
    .DataSource = dtExpense
    .DisplayMember = "acct_title"
    .ValueMember = "acct_id"
    .DataPropertyName = "acct_id"
    .ToolTipText = "description"
End With

谁能告诉我怎么做。在 datagriviewcell.tooltiptext 中,它必须在某个时候绘制。我正在考虑如何使用 datagridviewcomboboxcolumn 执行此操作,它必须显示组合框中的每个项目。

假设您有一个对象 class,其 string 属性名为 acct_title(显示为下拉项)和 description(显示为这些下拉项的工具提示项目),你会想要:

  1. 向窗体添加工具提示控件。
  2. 处理 DataGridView 的 EditingControlShowing 事件以将事件处理程序添加到基础 ComboBox。

    Me.DataGridView3.EditingControlShowing += DataGridView3_EditingControlShowing
    
    Private Sub DataGridView3_EditingControlShowing(sender As Object, e As DataGridViewEditingControlShowingEventArgs)
    If TypeOf e.Control Is ComboBox Then
            Dim cb As ComboBox = TryCast(e.Control, ComboBox)
            cb.DrawMode = DrawMode.OwnerDrawFixed
            cb.DrawItem -= Cb_DrawItem
            cb.DrawItem += Cb_DrawItem
            cb.DropDownClosed -= Cb_DropDownClosed
            cb.DropDownClosed += Cb_DropDownClosed
        End If
    End Sub
    
  3. 处理 ComboBox DrawItem 事件以设置工具提示值并显示它。我们将使用反射从下拉项中获取 description 属性 并将其字符串值设置为工具提示。

    Private Sub Cb_DrawItem(sender As Object, e As DrawItemEventArgs)
        Dim cb As ComboBox = TryCast(sender, ComboBox)
        Dim item = cb.Items(e.Index)
        Dim display As String = cb.GetItemText(item)
        Dim toolText As String = item.[GetType]().GetProperty("description").GetValue(item, Nothing).ToString()
    
        e.DrawBackground()
    
        Using br As New SolidBrush(e.ForeColor)
            e.Graphics.DrawString(display, e.Font, br, e.Bounds)
        End Using
    
        If (e.State And DrawItemState.Focus) = DrawItemState.Focus AndAlso cb.DroppedDown Then 
            Me.toolTip1.Show(toolText, cb, e.Bounds.Right, e.Bounds.Bottom, 2000)
        End If
    
        e.DrawFocusRectangle()
    End Sub
    
  4. 处理 ComboBox DropDownClosed 事件以隐藏工具提示。

    Private Sub Cb_DropDownClosed(sender As Object, e As EventArgs)
        Dim cb As ComboBox = TryCast(sender, ComboBox)
        Me.toolTip1.Hide(cb)
    End Sub