更改包含特定字符串的列表框中特定项目的颜色

5
我想要改变包含特定字符串的项目的颜色。
Private Sub ListBox2_DrawItem(ByVal sender As Object, ByVal e As System.Windows.Forms.DrawItemEventArgs) Handles ListBox2.DrawItem
    e.DrawBackground()
    If DrawItemState.Selected.ToString.Contains("specific string") Then
        e.Graphics.FillRectangle(Brushes.LightGreen, e.Bounds)
    End If

    e.DrawFocusRectangle()

那是我的代码,但它不能工作。

2
请更清晰地解释“不工作”的情况。我们需要更具体的描述出错的原因。是否有任何不同的情况发生?如果没有,您是否在那里设置了断点或日志记录语句以确保事件是否触发? - Joel Coehoorn
2
你是否将属性 DrawMode 设置为 DrawMode.OwnerDrawFixedDrawMode.OwnerDrawVariable - Steve
1个回答

14

好的,首先您需要将列表框的属性DrawMode设置为"OwnerDrawFixed",而不是Normal。否则,您永远不会触发DrawItem事件。当完成这一步骤后,一切都很简单。

Private Sub ListBox1_DrawItem(sender As System.Object, e As System.Windows.Forms.DrawItemEventArgs) Handles ListBox1.DrawItem
    e.DrawBackground()

    If ListBox1.Items(e.Index).ToString() = "herp" Then

        e.Graphics.FillRectangle(Brushes.LightGreen, e.Bounds)
    End If
    e.Graphics.DrawString(ListBox1.Items(e.Index).ToString(), e.Font, Brushes.Black, New System.Drawing.PointF(e.Bounds.X, e.Bounds.Y))
    e.DrawFocusRectangle()
End Sub

如果选择了,您将需要使用不同的颜色来修饰它。但这应该足以让您继续工作。您已经很接近了,记住这一点。 :)


如果我的条件是动态的,那么我该怎么做呢?这意味着我将 ListBox1.Items[e.index].tostring() 传递给我的数据库,并且我想检查返回值是否为 null,如果是,则更改颜色为黑色,否则为红色。 - user3217843
只需更改if语句以检查返回值上的IsDbNull或Is Nothing。 - WozzeC

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接