vb.net – IndexOf ComboBox对我不起作用
发布时间:2020-12-17 00:01:20 所属栏目:大数据 来源:网络整理
导读:VB2010.我正在尝试使用Enumeration单位的内容填充ComboBox.我已经设法用字典做了这个.就像是 Dim dUnits As New Dictionary(Of String,Integer)Dim da As StringFor Each enumValue As eUnits In System.Enum.GetValues(GetType(eUnits)) da = ConvertEnumTo
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) 当我加载我的表格运作良好.现在,用户可以选择要显示的默认单位.那么我试试吧 Dim defUnits As eUnits = eUnits.Feet Dim idx As Integer = cbo.Items.IndexOf(defUnits) 'doesnt work,returns a -1 cbo.SelectedIndex = idx 我已经做了一段时间的研究,并且相当肯定这与将值存储为字符串的ComboBox有关,实际上我正在搜索一个整数的枚举.不知道我是否有这个权利.无论如何,我似乎无法选择默认项目.我可以尝试另一种方法吗?
首先,你有一个整数集合,你正在搜索枚举值.为此,请尝试以下方法之一:
>将枚举值存储在字典中而不是字符串中: Dim dUnits As New Dictionary(Of String,eUnits) >将整数保留在Dictionary中,但在搜索ComboBox时使用枚举的整数值: Dim idx As Integer = cbo.Items.IndexOf(CInt(defUnits)) 但这还不行.您是数据绑定到Dictionary,这意味着cbo.Items中的项不是枚举类型,而是Dictionary中的元素类型(KeyValuePair(Of String,eUnits),假设为#1). 最简单的解决方案是设置组合框的SelectedValue属性而不是SelectedIndex.假设您使用上面的选项#1,这将是: cbo.SelectedValue = defUnits 如果您使用选项#2,则必须先将其转换为整数: cbo.SelectedValue = CInt(defUnits) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |