sin*_*zzy 5 vb.net combobox dictionary enumeration indexof
VB2010.我正在尝试使用Enumeration单位的内容填充ComboBox.我已经设法用字典做了这个.就像是
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)
Run Code Online (Sandbox Code Playgroud)
当我加载我的表格运作良好.现在,用户可以选择要显示的默认单位.那么我试试吧
Dim defUnits As eUnits = eUnits.Feet
Dim idx As Integer = cbo.Items.IndexOf(defUnits) 'doesnt work, returns a -1
cbo.SelectedIndex = idx
Run Code Online (Sandbox Code Playgroud)
我已经做了一段时间的研究,并且相当肯定这与ComboBox将值存储为字符串有关,实际上我正在搜索一个整数的枚举.不知道我是否有这个权利.无论如何,我似乎无法选择默认项目.我可以尝试另一种方法吗?
首先,您有一个整数集合,并且正在搜索枚举值。为此,请尝试以下操作之一:
将枚举值存储在字典中而不是字符串中:
Dim dUnits As New Dictionary(Of String, eUnits)
Run Code Online (Sandbox Code Playgroud)将整数保留在字典中,但在搜索组合框时使用枚举的整数值:
Dim idx As Integer = cbo.Items.IndexOf(CInt(defUnits))
Run Code Online (Sandbox Code Playgroud)但这还行不通。您数据绑定到 a Dictionary,这意味着 in 中的项目cbo.Items不是枚举类型,而是Dictionary 中元素的类型(KeyValuePair(Of String, eUnits)假设上面的#1)。
最简单的解决方案就是设置SelectedValue组合框的属性而不是SelectedIndex. 假设您使用了上面的选项 #1,这将是:
cbo.SelectedValue = defUnits
Run Code Online (Sandbox Code Playgroud)
如果您使用选项#2,则必须首先将其转换为整数:
cbo.SelectedValue = CInt(defUnits)
Run Code Online (Sandbox Code Playgroud)