【问题标题】:IndexOf a ComboBox just will not work for meIndexOf a ComboBox 对我不起作用
【发布时间】:2012-11-16 00:41:24
【问题描述】:

VB2010。我正在尝试使用单位枚举的内容填充 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)

当我加载运行良好的表单时。现在用户可以选择要显示的默认单位。那我试试

Dim defUnits As eUnits = eUnits.Feet
Dim idx As Integer = cbo.Items.IndexOf(defUnits) 'doesnt work, returns a -1
cbo.SelectedIndex = idx

我已经做了一段时间的研究,并且相当确定这与 ComboBox 将值存储为字符串有关,实际上我正在寻找一个整数枚举。不知道我有没有这个权利。无论如何,我似乎无法选择默认项目。我可以尝试其他方法吗?

【问题讨论】:

    标签: vb.net dictionary combobox enumeration indexof


    【解决方案1】:

    首先,您有一个整数集合,并且您正在搜索枚举值。为此,请尝试以下方法之一:

    1. 将枚举值存储在字典中而不是字符串中:

      Dim dUnits As New Dictionary(Of String, eUnits)
      
    2. 将整数保留在 Dictionary 中,但在搜索 ComboBox 时使用枚举的整数值:

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

    但是这还行不通。您已将数据绑定到Dictionary,这意味着cbo.Items 中的项目不是枚举类型,而是字典中元素的类型KeyValuePair(Of String, eUnits) 假设#1更多)。

    最简单的解决方案是设置组合框的SelectedValue 属性而不是SelectedIndex。假设您使用了上面的选项 #1,这将是:

    cbo.SelectedValue = defUnits
    

    如果您改用选项 #2,则必须先将其转换为整数:

    cbo.SelectedValue = CInt(defUnits)
    

    【讨论】:

    • 好吧,我没有为值 Dictionary(Of String, Integer) 存储字符串,而 enumValue 是一个整数。通过将字典更改为 Dictionary(Of String, eUnits) 我并没有真正改变任何东西,因为枚举仍然是一个正确的整数?
    • 对不起,我可能不是 100% 清楚。这是让你失望的整数。枚举的基础类型是整数,是的,但实际上,枚举和整数是不同的类型(实际上,枚举是基础值加上类型信息)。所以组合框正在寻找eUnits 类型的枚举值,当它找到的都是整数时,它就放弃了。
    • 明白了。我做了推荐的调整,但它仍然没有选择默认选项。我想知道我最后的手段是否是循环浏览组合框并尝试进行手动匹配。对于小列表来说还可以,但对于大列表来说性能很热门。
    • 顺便说一句,我尝试了 CInt(defUnits) 和 defUnits,但没有任何乐趣。我有点难过,但至少我知道为什么它不起作用。我可以更改为 ListOf 或 DataTable 吗?不知道这是否有帮助。
    • @sinDizzy 稍等片刻,我刚刚重新阅读了这个问题并意识到正在发生的另一件事——您可以在运行时检查cbo.Items(0) 的类型。可能是KeyValuePair...让我重新回答。
    猜你喜欢
    • 1970-01-01
    • 2015-01-08
    • 1970-01-01
    • 2017-06-26
    • 1970-01-01
    • 1970-01-01
    • 2018-08-11
    • 1970-01-01
    • 2017-02-02
    相关资源
    最近更新 更多