Satvir Singh
Satvir Singh

Reputation: 61

Filter a listview in vb.net

Currently I have a program that is able to write to a ListView with column named : number, time, description . This listview is not bound to anything data, I'm just basically writing into it using the code.

What I want to do is to have a TextBox, whereby if the user wants to look at particular number i.e. 2, when they type into the textbox, then I want the listview to only show data with number = 2. When there's nothing in the textbox, I want the listview to show all the data.

I have being looking around on the internet and I didn't seem to find a filter method. Does it even exist and if so how would I go about implementing this.

All help is appreciated.

Upvotes: 0

Views: 8215

Answers (2)

Reza Aghaei
Reza Aghaei

Reputation: 125207

While I recommend using a DataGridView with DataSource but in cases that you need to use ListView, you can use this solution.

You can filter your list view this way:

  • Define a member field as backup storage of items:
  • In form Load after adding items to list view, store each item in that member field
  • Put a TextBox and a Button on form and handle Click event of the Button and in the handler, first clear all items of ListView then each item from that backup storage that matches with criteria.

Member Field for Backup of Items

Private ItemsBackup As New List(Of ListViewItem)

Fill backup after loading items in ListView in the form Load event

For Each item As ListViewItem In ListView1.Items
    ItemsBackup.Add(item)
Next

Code of Filter

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Me.ListView1.BeginUpdate()

    Me.ListView1.Items.Clear()
    For Each item As ListViewItem In ItemsBackup
        If (item.Text = Me.TextBox1.Text Or String.IsNullOrEmpty(Me.TextBox1.Text)) Then
            Me.ListView1.Items.Add(item)
        End If
    Next

    Me.ListView1.EndUpdate()
End Sub

You can also use above code for TextChanged event of the TextBox.

Here is a test data:

For i = 1 To 30
    Dim item As New ListViewItem(i.ToString())
    item.SubItems.Add(DateTime.Now.AddHours(i))
    Me.ListView1.Items.Add(item)
Next

Upvotes: 2

Grammarian
Grammarian

Reputation: 6882

A normal .NET ListView can't do this without a considerable amount of work. So, you could use ObjectListView -- an open source wrapper around a standard .NET ListView -- which has already done all the work for you.

It has built-in filtering (and highlighting)

enter image description here

Upvotes: 0

Related Questions