Click here to Skip to main content
15,882,017 members
Articles / Programming Languages / C#
Technical Blog

Adding images to a combobox control

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
19 Feb 2013CPOL 9.8K   4  
Adding images to a combobox control.

This may sound a lot harder than it actually is.  So let's take a look at how to do it:

First, create or add a combobox to your form. You need to change DrawMode to DrawMode.OwnerDrawFixed or DrawMode.OwnerDrawVariable. The DrawMode.OwnerDrawFixed enumeration draws all of the combobox items at the same size. The DrawMode.OwnerDrawVariable enumeration draws each of the combobox items at its own size (although they can all be the same size). I also set the ItemHeight to 100 to allow the image enough room to be displayed.  You can also change the MaxDropDownItems to limit the number of items to something less or more than the standard 8 items.

VB
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
  Dim oXref As Xrefs
  Dim oBitmap As System.Drawing.Bitmap

  With ComboBox1
    .DrawMode = DrawMode.OwnerDrawVariable
    .ItemHeight = 100
    .DisplayMember = "Text"
    .ValueMember = "Image"
    oBitmap = My.Resources.faceplate001
    oXref = New Xrefs("Item 1", oBitmap)
    .Items.Add(oXref)
    oBitmap = My.Resources.faceplate002
    oXref = New Xrefs("Item 2", oBitmap)
    .Items.Add(oXref)
    oBitmap = My.Resources.faceplate003
    oXref = New Xrefs("Item 3", oBitmap)
    .Items.Add(oXref)
  End With
End Sub

Just to make it easier for me when I get data back from the combobox, I am using a class to contain related data:

VB
Friend Class Xrefs
  Public Property Text As String
  Public Property Image As Image
  Public Sub New()
    Me.New(Nothing, Nothing)
  End Sub
  Public Sub New(ByVal Text As String)
    Me.New(Text, Nothing)
  End Sub
  Public Sub New(ByVal Text As String, ByVal Image As Image)
    Me.Text = Text
    Me.Image = Image
  End Sub
End Class

The only thing left to do is draw the image as required by the control:

VB
Private Sub ComboBox1_DrawItem(sender As System.Object, _
       e As System.Windows.Forms.DrawItemEventArgs) Handles ComboBox1.DrawItem
  If e.Index > -1 Then
    Dim oXref As Xrefs = ComboBox1.Items(e.Index)
    e.DrawBackground()
    e.Graphics.DrawImage(oXref.Image, e.Bounds.Left, e.Bounds.Top)
  End If
End Sub

You need to call db so that the control paints the background properly.  This will include the times the mouse moves over or through an item in the drop down list.

This is what my example looks like:

Image 1

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United States United States
Long time software engineer who rambles occasionally about coding, best practices, and other random things.

Comments and Discussions

 
-- There are no messages in this forum --