tags:

views:

25

answers:

1

hi,

I am new to developing UI in .net. Basically I am using a listview and I want to search through items in listview. Suppose the list contains this:

Sno Name
1 Michael Jackson
2 John Mitchel

If I search usign the second or third term it should display all the items that match the criteria. I tried using .FindString, but it is just searching the first term. This is not what I want. Can anyone tell me a better way to do what I want?

Thanks in advance.

+1  A: 

Just repeatedly call ListBox.FindString() until you found them all. For example:

Public Class Form1
    Public Sub New()
        InitializeComponent()
        ListBox1.SelectionMode = SelectionMode.MultiExtended
    End Sub

    Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
        ListBox1.BeginUpdate()
        ListBox1.SelectedIndices.Clear()
        If TextBox1.Text.Length > 0 Then
            Dim index As Integer = -1
            Do
                dim found As integer = ListBox1.FindString(TextBox1.Text, index)
                If found <= index Then Exit Do
                ListBox1.SelectedIndices.Add(found)
                index = found
            Loop
        End If
        ListBox1.EndUpdate()
    End Sub
End Class

If you need to find a match on any part of the list box item string then you can search the items like this:

Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
    ListBox1.BeginUpdate()
    ListBox1.SelectedIndices.Clear()
    If TextBox1.Text.Length > 0 Then
        For index As Integer = 0 To ListBox1.Items.Count - 1
            Dim item As String = ListBox1.Items(index).ToString()
            If item.IndexOf(TextBox1.Text, StringComparison.CurrentCultureIgnoreCase) >= 0 Then
                ListBox1.SelectedIndices.Add(index)
            End If
        Next
    End If
    ListBox1.EndUpdate()
End Sub
Hans Passant