user11934472
user11934472

Reputation:

How to display the result using search button and textbox to listview

I'm coding a search button to listview and display the result data only

Private Sub Command3_Click()
    Dim itmx As ListItem
    Set itmx = Listview1.FindItem(Text3.Text, lvwText, , lvwPartial)

    If itmx Is Nothing Then
        MsgBox "record not found", vbCritical
    Else
        Listview1.ListItems(itmx.Index).Selected = True
        Listview1.SetFocus
    End If

End Sub

I expect the result will display only the data which I Search in textbox, the code above only highlighted the the row in listview.

Upvotes: 0

Views: 642

Answers (1)

Étienne Laneville
Étienne Laneville

Reputation: 5031

This code will select multiple items in your ListView matching your search criteria and remove those that don't:

Private Sub Command3_Click()
    Dim itmx As ListItem
    Dim iIndex As Integer
    Dim iRecordsFound As Integer
    Dim fMultiSelect As Boolean

    ' Store state of ListView's MultiSelect property and set it to True
    fMultiSelect = ListView1.MultiSelect
    ListView1.MultiSelect = True

    ' Deselect any selected items
    For iIndex = 1 To ListView1.ListItems.Count
        ListView1.ListItems.Item(iIndex).Selected = False
    Next

    ' Initialize variables
    iIndex = 1
    iRecordsFound = 0

    Do While iIndex > 0 And iIndex <= ListView1.ListItems.Count

        Set itmx = ListView1.FindItem(Text3.Text, lvwText, iIndex, lvwPartial)

        If itmx Is Nothing Then
            iIndex = 0
        Else
            itmx.Selected = True
            iIndex = itmx.Index + 1
            iRecordsFound = iRecordsFound + 1
        End If

    Loop

    ' Delete unselected items
    For iIndex = ListView1.ListItems.Count To 1 Step -1
        If Not ListView1.ListItems.Item(iIndex).Selected Then
            ListView1.ListItems.Remove iIndex
        End If
    Next

    If iRecordsFound = 0 Then
        MsgBox "No records found", vbCritical
    Else
        MsgBox iRecordsFound & " records found", vbInformation
    End If

    ' Restore state of ListView's MultiSelect property
    ListView1.MultiSelect = fMultiSelect

    ListView1.SetFocus

End Sub

Upvotes: 1

Related Questions