Change color of specific item on listbox that contains a specific string on drawitem

listbox, vb.net

Solution

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. :)

Problem

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

Original source