Using Enum with ComboBox and setting Combobox value –

This is my take on setting a combobox to use an enum which has both a description and key value set. It also shows how this works when trying to assign a value to the combobox.

Enum MyLogEnum
Error = 1
Warning = 2
Information = 3
End Enum

ComboBox_LogLevel.DataSource = System.Enum.GetValues(GetType(MyLogEnum))

And to assign a numeric value to the Combobox and make it display correctly:

ComboBox_LogLevel.SelectedItem = DirectCast(SourceIntValue, MyLogEnum)

Unfortunately, I could not find an equally as elegant way of doing the same thing using a ComboBox that was part of a Datagrid View, so ended up rewriting the Enum as a Dictionary like this:

Dim LoggingLevelsList As New Dictionary(Of String, Integer)
For Each enumValue As Integer In [Enum].GetValues(GetType(MyLogEnum))
LoggingLevelsList.Add([Enum].GetName(GetType(MyLogEnum), enumValue), enumValue)
DataGridCombo.DataSource = New Windows.Forms.BindingSource(LoggingLevelsList, Nothing)
DataGridCombo.DisplayMember = "Key"
DataGridCombo.ValueMember = "Value"

With this in the Datagridview Combobox, you do not need to do any casting from the source integer.

If someone has a better way for Enums on a DataGridView ComboBox, I would really like to hear them.

2 people found this post useful.

One thought on “Using Enum with ComboBox and setting Combobox value –

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.