Combobox Backcolor with Dropdownlist is possible?

2.3k views Asked by At

The items in the combobox do not appear. This is the code I have:

    ComboBox1.BackColor = Color.White
    ComboBox1.ForeColor = Color.Black
    ComboBox1.DrawMode = DrawMode.OwnerDrawFixed
    ComboBox1.DropDownStyle = ComboBoxStyle.DropDownList
    ComboBox1.FlatStyle = FlatStyle.Standard
    ComboBox1.Items.Add("LIne 1")
    ComboBox1.Items.Add("LIne 2")
    ComboBox1.Items.Add("LIne 3")
    ComboBox1.Items.Add("LIne 4")
    ComboBox1.Items.Add("LIne 5")
    ComboBox1.Items.Add("LIne 6")
    ComboBox1.Text = ComboBox1.Items(0)

And this is what I see when I execute it:

enter image description here

What am I doing wrong in my code?

1

There are 1 answers

0
rene On

This is the line that makes that you don't see any items:

ComboBox1.DrawMode = DrawMode.OwnerDrawFixed

That is because with that line you tell the Combobox: Hey, I'm doing the drawing myself. And from that moment onward the Combobox will raise the event DrawItem when it wants to draw something and it is up to you to subscribe to it and handle it. Handling in this case means: Draw something on the given Graphics object in the event.

Here is a simple implementation that does that:

Private Sub ComboBox1_DrawItem(sender As Object, e As DrawItemEventArgs) Handles ComboBox1.DrawItem
    Dim Brush = Brushes.Black
    If (e.State And DrawItemState.ComboBoxEdit) = DrawItemState.ComboBoxEdit Then
        Brush = Brushes.Yellow
    End If
    If (e.State And DrawItemState.Selected) = DrawItemState.Selected Then
        Brush = Brushes.SteelBlue
    End If

    Dim Point = New Point(2, e.Index * e.Bounds.Height + 1)

    ' reset 
    e.Graphics.FillRectangle(New SolidBrush(ComboBox1.BackColor),
        New Rectangle(
            Point,
            e.Bounds.Size))
    ' draw content
    e.Graphics.DrawString(
        ComboBox1.Items(e.Index).ToString(),
        ComboBox1.Font,
        Brush,
        Point)
End Sub

If you weren't planning on drawing your own items, you can off course remove the DrawMode line ...

Here is the result with my code:

owner drawn combobox