如何从DictionaryEntry中读取选定的值

时间:2018-10-31 17:40:01

标签: vb.net

我使用如下的DictionaryEntry值填充了一个ComboBox。

现在,如何从下拉框中读取选定的值? SelectedItem不起作用:抛出错误“参数'Prompt'无法转换为'String'类型。”

cboICSOverrideReason.DisplayMember = "Key"
cboICSOverrideReason.ValueMember = "Value"

cboICSOverrideReason.Items.Add(New DictionaryEntry("test1", 3))
cboICSOverrideReason.Items.Add(New DictionaryEntry("test2", 4))
cboICSOverrideReason.Items.Add(New DictionaryEntry("test3", 5))
cboICSOverrideReason.Items.Add(New DictionaryEntry("test4", 6))

2 个答案:

答案 0 :(得分:0)

ComboBox中的项目属于Object类型,因此您需要将其强制转换为DictionaryEntry(因为这就是您要放入的内容)。此外,DictionaryEntry的键和值也是Object类型,因此您也需要将其转换,如下所示:

myInteger = CInt(DirectCast(cboICSOverrideReason.SelectedItem, DictionaryEntry).Value)

答案 1 :(得分:0)

正如@dai所说,您实际上并没有绑定到数据源。要绑定数据,您应该执行以下代码中的.Load事件中的操作。该代码包括RemoveHandlerAddHandler to stop the。在添加数据并将事件重新订阅到代码中时,触发了SelectedIndexChanged`事件。

Dim mydata As New Dictionary(Of String, Integer)

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    RemoveHandler cboICSOverrideReason.SelectedIndexChanged, AddressOf cboICSOverrideReason_SelectedIndexChanged
    mydata.Add("test1", 3)
    mydata.Add("test2", 4)
    mydata.Add("test3", 5)
    mydata.Add("test4", 6)
    cboICSOverrideReason.DisplayMember = "Key"
    cboICSOverrideReason.ValueMember = "Value"
    cboICSOverrideReason.DataSource = New BindingSource(mydata, Nothing)
    AddHandler cboICSOverrideReason.SelectedIndexChanged, AddressOf cboICSOverrideReason_SelectedIndexChanged
End Sub



Private Sub cboICSOverrideReason_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboICSOverrideReason.SelectedIndexChanged
    MessageBox.Show(DirectCast(cboICSOverrideReason.SelectedValue, Integer))
End Sub

返回的值始终是一个对象,因此您需要将其转换为适当的类型。因此,如果您的值应为整数,则需要类似

DirectCast(cboICSOverrideReason.SelectedValue, Integer)