Search code examples
vb.netlistviewsearch

How to search in listview


I am trying to create a Loop that will read through the information on my ListView through the SubItem to find the text that matches the text in my Textbox whenever I hit the search button and Focuses the listbox onto the matched text. Below is what I have but it keeps telling me that the value of string cannot be converted. I am also pretty sure that my numbers wont loop correctly but I am not really sure how to cause them to loop endlessly till end of statement.

    Dim T As String
    T = Lines.Text
    For r As Integer = 0 to -1
        For C As Integer = 0 to -1
            If List.Items(r).SubItems(C).Text = Lines.Text Then
                List.FocusedItem = T
            End If
        Next
    Next

End Sub

Solution

  • Instead of looping like that through the ListView, try using a For Each instead:

    searchstring as String = "test1b"
    ListView1.SelectedIndices.Clear()
    For Each lvi As ListViewItem In ListView1.Items
        For Each lvisub As ListViewItem.ListViewSubItem In lvi.SubItems
            If lvisub.Text = searchstring Then
                ListView1.SelectedIndices.Add(lvi.Index)
                Exit For
            End If
        Next
    Next
    ListView1.Focus()
    

    This will select every item which has a text match in a subitem. Don't put this code in a form load handler, it won't give the focus to the listview and the selected items won't show. Use a Button click handler instead.