After a break in July (for many reasons – mainly missing time between projects at work and summer holidays!), I am back with another article.

By pure coincidence, my previous article (June) and this current one are both related to the combo box control.

This month, we will add images to the dropdown part of the combo. If you have read my June’s article, you will find that it is exactly the same mechanism to initialize and draw custom items that are used to be able to display images. It is in fact so close, that I will reuse the demo code from the June article as the base for this month. If you haven’t read last month article, you better take 5 minutes to review it as I won’t re-explain what was in there!

This month’s downloadable code

This month solution contains both VB and C# projects. The solution was created using Visual Studio 2017 but the code should work as well in older version of the.Net Framework.

Figure 1: The demo application in action

Modifying the ComboBoxItem class

Each item displayed in the combo box, will now be able to show a small icon on the left of the text. To achieve this behavior, we need to add a new property to the ComboBoxItem class created last month.

This new property is called ImageIndex and it contains the index of the image we will display.

Public Class ComboboxItem
Public Text As String
Public Value As Object
Public Selectable As Boolean = True
Public ImageIndex As Integer = -1
Public Overrides Function ToString() As String
Return Text
End Function
End Class

Because we will need some icons, surely the easiest way is to drop an Image List control on our form and populate it with the images we want.

I have dropped that control to my form and added 5 random icons in its Images collection just for the demo. Notice that like most index value, the images collection is 0 based.

Figure 2: Setting up the Image List control

Filling the combo box

Last month, when we wanted to fill our combo box with values, we needed to add instances of the ComboboxItem into the Items collection. We need to do exactly the same thing here and just add the index of the related image (added to Image List Images collection) which is a new property of the ComboboxItem class.

Notice that we don’t have to set an image if we don’t need one for some items. It will just not show any icon for that specific item but will keep the text correctly aligned.

Adding icons when drawing the items

The last thing we need to do is to draw the icons in the drop down if the ImageIndex is set. This is done in the DrawItem event handler just like we used in the previous article to fade the un-selectable items (which we still do).