首页 > 解决方案 > VB.Net - 如何在受字典限制的列表框中搜索?

问题描述

所以我有一个由 ID(键)和名称(值)限制的列表框。这是我用来将字典绑定到列表框的方法:

listCustomer.DataSource = Nothing
listCustomer.Items.Clear()

Dim listCustomerSource As New Dictionary(Of String, String)()
While (dr.Read())
    listCustomerSource.Add(dr.GetString(0), dr.GetString(1))
End While

listCustomer.DataSource = New BindingSource(listCustomerSource, Nothing)
listCustomer.DisplayMember = "Value"
listCustomer.ValueMember = "Key"

这是我在 textbox_textchange 中的方法:

Private Sub searchList(ByVal textbox As TextBox, ByVal listbox As ListBox)
    Dim hits = From item In listbox.Items.Cast(Of String)() Where (item.IndexOf(textbox.Text, StringComparison.OrdinalIgnoreCase) >= 0)
    If hits.Any Then
        listbox.SelectedItem = hits.First()
    Else
        listbox.ClearSelected()
    End If
End Sub

我已经在只有一个文本(未绑定)的列表框中尝试过它,它工作得很好,但是如果我在有界字典的列表框中使用它,它会收到错误“无法转换类型为 'System.Collections.Generic 的对象。 KeyValuePair`2[System.String,System.String]' 键入'System.String'。在文本框中输入

标签: vb.net

解决方案


发生这种情况是因为当您绑定数据源时,项目不再是简单的字符串,而是数据源的实例。当您绑定 Dictionary 时,ListBox 中的每个项目都是 KeyValuePair 类的实例。在 DisplayMember 或 ValueMember 上设置的值仅用于 ListBox 的显示目的,您的项目都是KeyValuePair(Of String, String)

因此,您只需要将搜索匹配项的行更改为

Dim hits = From item In l.Items.Cast(Of KeyValuePair(Of String, String))() 
           Where (item.Value.IndexOf(x, StringComparison.OrdinalIgnoreCase) >= 0)

推荐阅读