Change the color of a specific item in a list containing a specific string in drawitem

I want to change the color of an element 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()

this is my code but not working

+5
source share
1 answer

Ok, first you need to set the DrawMode property from the list to "OwnerDrawFixed" instead of Normal. Otherwise, you cannot fire the DrawItem event. When this is done, everything is pretty straightforward.

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 it with different colors, if selected. But that should be enough for you to keep working. You were close, remember this. :)

+9
source

All Articles