在vb.net中使用文本框过滤列表框

时间:2016-03-01 14:58:58

标签: vb.net for-loop filter textbox listbox

我已经添加了一个名字很多的列表框,现在我想尝试做一个简单的过滤器(使用up或low case并不重要,我的意思是如果用户会写上textbox" apple&#34 ;,列表框总是显示它的结果)用于查找使用列表框名称写在文本框上的字符串。 我已经尝试过这种方式循环,(检查所有索引),但我不知道如何检查if:

Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
        For counter As Integer = 0 To ListBox1.Items.Count - 1
            If InStr(ListBox1.Items(counter).ToString, TextBox1.Text) Then

            End If
            Next
End Sub

2 个答案:

答案 0 :(得分:0)

如果要搜索子字符串,请使用String.IndexOf之类的.NET方法:

Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
    For counter As Integer = 0 To ListBox1.Items.Count - 1
        Dim item = ListBox1.Items(counter).ToString()
        Dim containsText = item.IndexOf(TextBox1.Text, StringComparison.CurrentCultureIgnoreCase) >= 0
        If containsText Then

        End If
    Next
End Sub

如果要过滤此ListBox,可以使用以下LINQ查询:

Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
    Dim items = From it In ListBox1.Items.Cast(Of Object)()
                Where it.ToString().IndexOf(TextBox1.Text, StringComparison.CurrentCultureIgnoreCase) >= 0
    Dim matchingItemList As List(Of Object) = items.ToList()
    ListBox1.BeginUpdate()
    ListBox1.Items.Clear()
    For Each item In matchingItemList
        ListBox1.Items.Add(item)
    Next
    ListBox1.EndUpdate()
End Sub

答案 1 :(得分:0)

它是c# question的副本。这是翻译的代码。

Public Sub t1_TextChanged(sender As Object, e As TextChangedEventArgs)
    If [String].IsNullOrEmpty(t1.Text.Trim()) = False Then
        lb1.Items.Clear()
        For Each str As String In list
            If str.StartsWith(t1.Text.Trim()) Then

                lb1.Items.Add(str)
            End If
        Next

    ElseIf t1.Text.Trim() = "" Then
        lb1.Items.Clear()

        For Each str As String In list
            lb1.Items.Add(str)
        Next
    End If
End Sub