Introduction
This is a simple combobox that displays icons to the user. It is similar to the imageComboBox
in VB. I saw many examples like this made in C#, so I decided to make a VB one.
You have to create an ImageList
, load images to it and then set the ComboIcon.ImageList
property to this ImageList
. Once this is done you can add items. I made also a class for the Item (ComboBoxIconItem
) which is a simple class that stores the imageIndex
(in the imageList) of the item and its text.
The ComboIcon
Class inherits from the ComboBox
of course. It has just an Override
to the Draw_Item
Sub. In the override we make the combo Owner_draw
and we draw the icon and text in case there is an imageIndex
in the ImageList
for the Icon
. If not, we load only the text to the combo.
Code
The ComboIcon
class has these Overrides:
Private ListaImg1 As New ImageList
Public Sub New()
DrawMode = DrawMode.OwnerDrawFixed
End Sub
Protected Overrides Sub OnDrawItem(ByVal e _
As System.Windows.Forms.DrawItemEventArgs)
e.DrawBackground()
e.DrawFocusRectangle()
Dim item As New ComboBoxIconItem
Dim imageSize As New Size
imageSize = ListaImg1.ImageSize
Dim bounds As New Rectangle
bounds = e.Bounds
Try
item = Me.Items(e.Index)
If (item.ImageIndex <> -1) Then
Me.ImageList.Draw(e.Graphics, bounds.Left, _
bounds.Top, item.ImageIndex)
e.Graphics.DrawString(item.Text, e.Font, _
New SolidBrush(e.ForeColor), bounds.Left + _
imageSize.Width, bounds.Top)
Else
e.Graphics.DrawString(item.Text, e.Font, _
New SolidBrush(e.ForeColor), bounds.Left, _
bounds.Top)
End If
Catch ex As Exception
If (e.Index <> -1) Then
e.Graphics.DrawString(Items(e.Index).ToString(), e.Font, _
New SolidBrush(e.ForeColor), bounds.Left, bounds.Top)
Else
e.Graphics.DrawString(Text, e.Font, _
New SolidBrush(e.ForeColor), bounds.Left, bounds.Top)
End If
End Try
MyBase.OnDrawItem(e)
End Sub
That's it. The ComboBoxIconItem
is very simple, it just has 2 properties: text
and imageIndex
, that is the imageindex of the image in the imagelist that should be displayed with the Item.
Using the code
So, in the Form
, or where you want to put the comboBox
you just have to write this code:
Dim MyCombo As New ComboIcon
MyCombo.ImageList = ImageList1
MyCombo.Items.Add(New ComboBoxIconItem("Bart", 0))
MyCombo.Items.Add(New ComboBoxIconItem("Marge", 2))
MyCombo.Items.Add(New ComboBoxIconItem("Homer", 1))
MyCombo.Items.Add(New ComboBoxIconItem("Lisa", 3))
MyCombo.Items.Add(New ComboBoxIconItem("Maggie", 4))
Me.Controls.Add(MyCombo)
MyCombo.Top = 30
MyCombo.Left = 50
Conclusion
That's all. I hope this is useful to you.