user2262237
user2262237

Reputation:

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

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

Upvotes: 5

Views: 32737

Answers (1)

WozzeC
WozzeC

Reputation: 2660

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

Upvotes: 15

Related Questions