Change color of specific item on listbox that cont

2019-04-09 00:52发布

问题:

i want to change the color of item that contains a specific string

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()

that is my code but not working

回答1:

Alright, first you need to set the property DrawMode of the list box to "OwnerDrawFixed" instead of Normal. Otherwise you will never get the DrawItem event to fire. When that is done it is all pretty straight forward.

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

You will have to touch this up with different colors if selected. But this should be enough for you to continue to work on. You were close, keep that in mind. :)