vb.net - 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'。在文本框中输入
解决方案
发生这种情况是因为当您绑定数据源时,项目不再是简单的字符串,而是数据源的实例。当您绑定 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)
推荐阅读
- r - config::get 在打包的闪亮应用程序中使用时冻结
- python - Discord py 清除通道
- reactjs - 无法获取 HTMLElement 的值
- php - 用 php 和 simplexml_load_file 解析 xml 文件忘记换行
- javascript - 如何根据位置打印出某些元素?
- r - 在 R 中绘制 native-land.ca json
- java - 如何在 kotlin 中修改或生成代码?(不仅是 JVM)
- google-cloud-platform - 谷歌函数构建失败:发现不兼容的依赖项(Python)
- go - 使用反射确定结构字段是否不完整 Cgo 类型
- reactjs - useMemo 不影响组件渲染