2012-07-10 45 views
0

我试图使TextBox1成为一个搜索栏,以搜索ListBox1中的特定字符串。vb.net listbox search

我希望它删除没有我搜索的字符串的其他项目。例如,如果列表包含(奶酪,鸡蛋,牛奶,鸡肉,巧克力),那么搜索“ch”只会显示奶酪,鸡肉和巧克力。这可能吗?

此代码我在这里搜索字符串,但不会消除其他字符。

编辑: - 这些都是非常好的回应,但我不能使用它们中的任何一个,因为列表框正在填充来自特定目录的文件名,这给我这个错误;

设置DataSource属性时无法修改项目集合。

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 

我感谢所有帮助。谢谢。

回答

2

要以这种方式进行这项工作,您需要列出所有项目的记忆,然后ListBox1只会显示匹配项。否则,当用户点击退格键缩短搜索词组时,原始项目都不会返回。因此,在TextBox1_TextChanged事件中,执行此操作的最简单方法是清除ListBox1,然后循环访问内存中的所有项目,然后只添加与ListBox1匹配的项目。例如:

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 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固有支持此功能。

+0

感谢您的回复,但在此行代码中, For Each item As String In allItems allItems is not declared? – 2012-07-10 18:33:48

+0

@MattLevesque我更新了我的答案以解释所有项目。 – 2012-07-10 18:46:37

1
Dim lstBindTheseStrings As List(Of Object) = (From objString As Object _ 
                In ListBox1.Items _ 
                Where CStr(objString).StartsWith(TextBox1.Text)).ToList() 

    ListBox1.DataSource = lstBindTheseStrings 

    ListBox1.SelectedIndex = If((ListBox1.FindString(TextBox1.Text) > -1), _ 
           ListBox1.FindString(TextBox1.Text), -1) 

编辑:

上面的代码将过滤什么最初在列表框。 SteveDog的解决方案更多的是你正在寻找的东西,但是你可以用你的AllItems列表来替换我的Linq语句中的ListBox1.Items以达到你想要的位置。

0

SteveDog的解决方案就是你想要的方式,所以你不必在每次搜索后重新填充列表框。然而,如果你设置在那条路上......

Dim i As Integer 
    For i = 0 To ListBox1.Items.Count - 1 
     If i > ListBox1.Items.Count - 1 Then Exit For 
     If Not ListBox1.Items(i).Contains(Textbox1.Text) Then 
      ListBox1.Items.Remove(ListBox1.Items(i)) 
      i -= 1 
     End If 
    Next 

虽然似乎很麻烦,不是吗?