Tuesday, February 26, 2008

How to have different colors for different items in a combobox in VB.NET

I have a drop down style combobox in VB.NET 2003, and I would like to assign different colors to different items in the combobox.  I came across the following article on vbcity:

The article shows you how to add images to combobox items and different colors.  You  can also download code and try things out yourself.  However, for me all I wanted was to color different items a different color.  Using some of the concepts from the article,  this is how one can do such a thing:

1.  The first thing one needs to do, in the drawmode property of the Combo Box, to select either OwnerDrawFixed, OwnerDrawVariable.
2.  Next, in the DrawItem Event the user can do something the the following:

        Dim g As Graphics = e.Graphics

        Dim bBlue As SolidBrush = New SolidBrush(Color.Blue)
        Dim bRed As SolidBrush = New SolidBrush(Color.Red)
        Dim bOrange As SolidBrush = New SolidBrush(Color.Orange)

            If e.Index = 0 Then
                g.DrawString("Value1", Me.ComboBox1.Font, bBlue, e.Bounds.Left, e.Bounds.Top)
            ElseIf e.Index = 1 Then
                g.DrawString("Valu2", Me.ComboBox1.Font, bRed, e.Bounds.Left, e.Bounds.Top)
                g.DrawString("Value3", Me.ComboBox1.Font, bOrange, e.Bounds.Left, e.Bounds.Top)
            End If

This basically colors the first value, Blue, the second value Red and everything else Orange.

No comments: