Public Class Pic_combobox
Inherits ComboBox
'this class is for the example, can be replaced by anything and put outside the combobox class , it is here for convenience only
Public Class Dice
Property Name As String = ""
Property Picture As Image = Nothing
Property Value As Integer = 0
Public Overrides Function ToString() As String
Return Name
End Function
End Class
' the list of items to put in the combobox, same can be put outside the class, it is here for convenience only
Public list_dice As New List(Of Dice) From {
New Dice With {.Name = "D4", .Value = 4, .Picture = My.Resources.D4},
New Dice With {.Name = "D6", .Value = 6, .Picture = My.Resources.D6},
New Dice With {.Name = "D8", .Value = 8, .Picture = My.Resources.D8},
New Dice With {.Name = "D10", .Value = 10, .Picture = My.Resources.D10},
New Dice With {.Name = "D12", .Value = 12, .Picture = My.Resources.D12},
New Dice With {.Name = "D20", .Value = 20, .Picture = My.Resources.D20},
New Dice With {.Name = "D100", .Value = 100, .Picture = My.Resources.D100}
}
Public Sub New()
Me.DropDownStyle = ComboBoxStyle.DropDownList
Me.DrawMode = Windows.Forms.DrawMode.OwnerDrawVariable
MyBase.Items.Clear()
MyBase.Items.AddRange(list_dice.ToArray)
End Sub
Protected Overrides Sub OnDrawItem(ByVal e As System.Windows.Forms.DrawItemEventArgs)
'when control is created with designer, it adds 2 times the items, this will remove them
' if the control is created via code, it works correctly and the following code is not needed
If MyBase.Items.Count > 7 Then
For i = MyBase.Items.Count - 1 To 7 Step -1
MyBase.Items.RemoveAt(i)
Next
End If
Dim d As New Dice With {.Name = "", .Value = 0, .Picture = My.Resources.D100}
If e.Index <> -1 Then
d = list_dice(e.Index)
End If
If (e.State And DrawItemState.ComboBoxEdit) = DrawItemState.ComboBoxEdit Then
' Draw the contents of the edit area of the combo box.
e.Graphics.DrawImage(d.Picture, New Point(2, e.Bounds.Top + 2))
e.Graphics.DrawString(If(d.Name = Nothing, "Empty", d.Name), Me.Font, Brushes.Black, 65, e.Bounds.Top + 22)
Else
' Draw the contents of an item in the drop down list.
e.Graphics.DrawImage(d.Picture, New Point(2, e.Bounds.Top + 2))
e.Graphics.DrawString(d.Name, Me.Font, Brushes.Black, 65, e.Bounds.Top + 22)
' Draw the focus rectangle.
e.DrawFocusRectangle()
End If
MyBase.OnDrawItem(e)
End Sub
End Class