Dailycode.info

Short solution for short problems

Override combobox item style. (Windows.Forms)

 

I was thinking of a way to show the status of items in a dropdown list in a nice way.

After some googling around I found a pretty nice solution. You can change the color of the text depending on certain values or even draw a rectangle or circle in front of the items. I choose the last solution. A green item would mean that it’s correctly in the database, blue means it’s in the database but with some modifications to be done. Red means it’s not yet in the database.

Here’s how it looks:

 

The implementation needs 2 things. First you have to set the DrawMode to ‘OwnerDrawVariable’.

Then you can override the DrawItem event. Here’s an example of the implementation I did. It is in VB.net this time since my current workplace has VB.Net written programs.

Private Sub ComboBox1_DrawItem(ByVal sender As Object, _

        ByVal e As System.Windows.Forms.DrawItemEventArgs) _

        Handles cmbTable.DrawItem

 

        Dim size As Single

        Dim myFont As System.Drawing.Font

        Dim family As FontFamily

 

        Dim rectColor As New System.Drawing.Color

        Dim tableName As String = dsTables.Tables(0).Rows(e.Index)("TABLE_NAME")

        If tableDiffThenInDBHashtable.Contains(tableName) Then

            size = 9

            rectColor = System.Drawing.Color.Blue

            family = Me.Font.FontFamily

        ElseIf tableInDBHashtable.Contains(tableName) Then

            size = 8

            rectColor = System.Drawing.Color.Green

            family = Me.Font.FontFamily

        Else

            size = 9

            rectColor = System.Drawing.Color.Red

            family = Me.Font.FontFamily

        End If

 

        ' Draw the background of the item.

        e.DrawBackground()

 

        ' Create a square filled with the color.

        Dim rectangle As Rectangle = New Rectangle(2, e.Bounds.Top + 2, _

            e.Bounds.Height, e.Bounds.Height - 4)

        e.Graphics.FillRectangle(New SolidBrush(rectColor), rectangle)

 

        ' Draw each string in the datasource, using a size, color, and font for each item.

        myFont = New Font(family, size, FontStyle.Regular)

        e.Graphics.DrawString(dsTables.Tables(0).Rows(e.Index)("TABLE_NAME"), myFont, System.Drawing.Brushes.Black, _

            New RectangleF(e.Bounds.X + rectangle.Width, e.Bounds.Y, _

            e.Bounds.Width, e.Bounds.Height))

 

        ' Draw the focus rectangle if the mouse hovers over an item.

        e.DrawFocusRectangle()

    End Sub

 

I have filled some hash tables to quickly check the value of the item and decide which color to appoint.

Now it looks like this: