Reputation: 3800
I can set forecolor for listbox items using DrawItem event. However, for example, if my list contains a single red color item, once I add next one with desired green color, I am not able to remain first item with red color. Assuming that I can set color but I need to first get item color. How to get forecolor of a listbox item? Thank you.
Private Sub ListBox1_DrawItem(ByVal sender As Object, ByVal e As System.Windows.Forms.DrawItemEventArgs) Handles ListBox1.DrawItem
e.DrawBackground()
If e.Index = listBoxSize Then
e.Graphics.DrawString(ListBox1.Items(e.Index), e.Font, Brushes.Green, e.Bounds.X, e.Bounds.Y)
Else
Using br = New SolidBrush(e.ForeColor)
e.Graphics.DrawString(ListBox1.Items(e.Index), e.Font, br, e.Bounds.X, e.Bounds.Y)
End Using
End If
e.DrawFocusRectangle()
End Sub
Upvotes: 0
Views: 2976
Reputation: 6849
You can use Dictionary(TKey, TValue)
class to store the color for the listed items
Dim colors As New Dictionary(Of Integer, Color)
Private Sub ListBox1_DrawItem(ByVal sender As Object, ByVal e As System.Windows.Forms.DrawItemEventArgs) Handles ListBox1.DrawItem
e.DrawBackground()
Dim clr As Color = e.ForeColor
If e.Index = listBoxSize Then
clr = Colors.Green
Using br = New SolidBrush(clr)
e.Graphics.DrawString(ListBox1.Items(e.Index), e.Font, br, e.Bounds.X, e.Bounds.Y)
End Using
colors.Add(e.Index, clr)
e.DrawFocusRectangle()
End Sub
now you can retrive the color by List Index.
Dim clr Color = colors(listBox1.SelectedIndex)
Upvotes: 1