I am trying to filter a ListBox based on the presence of a string. Basically, if there is a ListItem that doesn\'t contain the string then I want to remove all ListItems that do
Let suppose the filter string is a textbox string and you want to filter your listbox according to the text changed in textbox. Let the name of the textbox is TB_Filter
.
Place this line of code from the top of your codes, after Public Class Form1
to temporary hold your listbox items.
Dim TempHoldMyItems As New ArrayList
Now use this piece of codes in your form_load event to update the temporary list from your listbox items.
TempHoldMyItems.Clear()
TempHoldMyItems.AddRange(listbox1.Items)
Ok, Now you can filter your listbox items according to the text in TB_Filter. Use this codes in TB_Filter Text Changed event.
listbox1.Items.Clear()
For Each item As String In TempHoldMyItems
If item.Length >= TB_Filter.Text.Length Then
If item.Substring(0, TB_Filter.Text.Length) = TB_SearchInSelected.Text Then
listbox1.Items.Add(item)
End If
End If
Next
This will filter items in listbox1 as you will type in TB_Filter. This will match starting of your items with your filter word in TB_Filter.
By making little changes (i.e. Instead of substring
you may use contains
property) to check filter query is contains in item.
listbox1.Items.Clear()
For Each item As String In TempHoldMyItems
If item.Contains(TB_Filter.Text) Then
listbox1.Items.Add(item)
End If
Next