IndexOf a ComboBox just will not work for me

combobox, dictionary, enumeration, indexof, vb.net

Solution

First of all you have a collection of integers and you're searching for the enum value. For that, try one of the following:

Store the enum value in the dictionary instead of a string:

Dim dUnits As New Dictionary(Of String, eUnits)

Keep the integers in the Dictionary but use the integer value of the enum when searching the ComboBox:

Dim idx As Integer = cbo.Items.IndexOf(CInt(defUnits))

But this is not going to work yet. You are data-bound to a `Dictionary`, which means the items in `cbo.Items` are not of the enum type, but of the type of the elements in the Dictionary (`KeyValuePair(Of String, eUnits)` assuming #1 above).

The easiest solution is just to set the `SelectedValue` property of the combo box instead of the `SelectedIndex`. Assuming you used option #1 above, this would be:

cbo.SelectedValue = defUnits

If you used option #2 instead, you'll have to convert this to an integer first:

cbo.SelectedValue = CInt(defUnits)

Problem

VB2010. I am trying to populate a ComboBox with the contents of an Enumeration of units. I have managed to do this with a Dictionary. Something like ``` Dim dUnits As New Dictionary(Of String, Integer) Dim da As String For Each enumValue As eUnits In System.Enum.GetValues(GetType(eUnits)) da = ConvertEnumToCommonName 'gets unique name for an enumeration dUnits.Add(da, enumValue) Next cbo.DisplayMember = "Key" 'display the the common name cbo.ValueMember = "Value" 'use the enumeration as the value cbo.DataSource = New BindingSource(dUnits, Nothing) ``` When I load up my form that works well. Now the user can choose to select a default unit to display. So then I try ``` Dim defUnits As eUnits = eUnits.Feet Dim idx As Integer = cbo.Items.IndexOf(defUnits) 'doesnt work, returns a -1 cbo.SelectedIndex = idx ``` I have been doing some research for some time and am fairly sure that this has to do with the `ComboBox` storing Values as a string and in reality I'm searching for an enumeration which is an integer. Don't know if I have that right or not. Anyway, I just cant seem to get the default item selected. Is there another approach I can try?

Original source