我试图让 TextBox1
成为一个搜索栏,以在 ListBox1
中搜索特定的字符串。
我希望它删除没有我搜索的字符串的其他项目。例如,如果列表包含(奶酪、鸡蛋、牛奶、鸡肉、巧克力),则搜索“ch”将只会显示奶酪、鸡肉和巧克力。这可能吗?
我这里的这段代码将搜索字符串,但不会消除其他字符串。
编辑:-这些都是非常好的响应,但我不能使用它们中的任何一个,因为列表框由特定目录中的文件名填充,这给了我这个错误;
Items collection cannot be modified when the DataSource property is set.
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
Dim i As Integer = ListBox1.FindString(TextBox1.Text)
ListBox1.SelectedIndex = i
If TextBox1.Text = "" Then
ListBox1.SelectedIndex = -1
End If
End Sub
我很感激任何帮助。谢谢。
最佳答案
要以这种方式工作,您需要在内存中列出所有项目,然后 ListBox1
将只显示匹配项。否则,当用户点击退格键来缩短他们的搜索短语时,所有原始项目都不会返回。因此,在 TextBox1_TextChanged
事件中,执行此操作的最简单方法是清除 ListBox1
,然后遍历内存中的所有项目,然后将匹配的项目添加到列表框 1
。例如:
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
ListBox1.Items.Clear()
For Each item As String In allItems
If item.StartsWith(TextBox1.Text, StringComparison.CurrentCultureIgnoreCase) Then
ListBox1.Items.Add(item)
End If
Next
End Sub
在此示例中,allItems
是所有项目的内存列表。如果您的项目是字符串,就像它们看起来那样,那么我建议将其设为 List(Of String)
并在类/表单级别将其声明为私有(private)字段:
private allItems As New List(Of String)()
然后,您需要在某处填充列表,可能是在表单的 Load
事件中:
allItems.Add("cheese")
allItems.Add("eggs")
allItems.Add("milk")
allItems.Add("chicken")
allItems.Add("chocolate")
但是,如果您只需要一个自动完成的文本框,那么重新发明轮子是愚蠢的。 WinForm TextBox
控件通过其 AutoComplete
属性固有地支持此功能。
关于vb.net 列表框搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11418685/