首页 > 解决方案 > How to collect a certain string anywhere in an item in a ListBox?

问题描述

I have been trying to find out how to collect a string anywhere in a Listbox, I use Visual Basic 2010 and this is more of an request, but there is code I found so you fix the code I found or tell me me an another code to use.

I have tried using ListBoxName.Items.Contains but that did not work, I tried a lot of methods and it would be hard to say all of then at once.

        ' Split string based on space
        Dim textsrtring As String = ListBox.Text
        Dim words As String() = textsrtring.Split(New Char() {" "c})
        Dim found As Boolean = False

        ' Use For Each loop over words
        Dim word As String
        For Each word In words
            If ListBox.Items.Contains(word) Then
                found = True

                Exit For
            End If
        Next

        MessageBox.Show(found)

They were no errors, the message box that appeared kept on telling me false and there is no string when I clearly put it in, no error messages.

标签: visual-studio-2010

解决方案


您需要一个内部循环来使用 String.Contains() 查看每个单词是否包含在您的主列表框条目中:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim searchFor As String = TextBox1.Text.Trim
    If searchFor.Length > 0 Then
        Dim words As String() = searchFor.Split(New Char() {" "c})
        Dim found As Boolean = False
        Dim foundAt As Integer
        ' Use For Each loop over words
        Dim word As String
        For Each word In words
            For i As Integer = 0 To ListBox.Items.Count - 1
                If ListBox.Items(i).ToString.Contains(word) Then
                    found = True
                    foundAt = i
                    Exit For
                End If
            Next
            If found Then
                Exit For
            End If
        Next
        If found Then
            ListBox.SelectedIndex = foundAt
            Label1.Text = "Search string found."
        Else
            ListBox.SelectedIndex = -1
            Label1.Text = "Search string NOT found."
        End If
    Else
        ListBox.SelectedIndex = -1
        Label1.Text = "No search string."
    End If
End Sub

推荐阅读