Search code examples
vb.netlistviewsearchfiltertextchanged

VB.NET Listview Textchanged Search


I've tried searching on stackoverflow and implementing code that I found but to no avail. As the text changes I want to use the current text in the textbox to filter through the listview items (so the items that are not closed to being matched get removed) and it only leaves me with whatever is contained in the columns.

Here's an example of what I mean:

Search: "Georges"

|1|Anderson Silva|Anderson silva is the champion in the ...|

|2|Georges St-Pierre| Georges is the champion in the ...|

|3|Georges Sotoropolis| Georges Sotoropolis is a fighter in the lightweight division|

With this search, only rows 2 and three would be returned. The first row would be omitted and not displayed. Once I erase the terms, then it would get displayed.

Here is the code that I currently have:

Private Sub tbSearch_TextChanged(sender As Object, e As System.EventArgs) Handles tbSearch.TextChanged
    lwArticles.BeginUpdate()

    If tbSearch.Text.Trim().Length = 0 Then
        'Clear listview
        lwArticles.Clear()

        'If nothing is in the textbox make all items appear
        For Each item In originalListItems
            lwArticles.Items.Add(item)
        Next
    Else
        'Clear listview
        lwArticles.Clear()

        'Go through each item in the original list and only add the ones which contain the search text
        For Each item In originalListItems
            If item.Text.Contains(tbSearch.Text) Then
                lwArticles.Items.Add(item)
            End If
        Next
    End If
    lwArticles.EndUpdate()

End Sub

It seems to be working but I cannot see the listview items once I enter something in the tbSearch. The scrollbar gets smaller / larger depending if there are more / less items due to the search being executed. My problem seems that they are not visible

Thank you!


Solution

  • Listview.Clear wipes out the items, columns, and groups. It appears you only want to wipe out the items, so call lwArticles.Items.Clear instead of lwArticles.Clear