Visual Basic Programming Code Examples
Visual Basic > Forms Code Examples
Find an item in a listview
Find an item in a listview
The following function can be used to find an item in a listview.
Option Explicit
'---Possible values for lFindType (must be declared in a Standard Module)
Public Const LVM_FIRST = &H1000, LVM_FINDITEM = (LVM_FIRST + 13)
Public Const LVFI_PARAM = &H1, LVFI_STRING = &H2
Public Const LVFI_PARTIAL = &H8, LVFI_WRAP = &H20
Public Const LVFI_NEARESTXY = &H40
Private Type POINTAPI
x As Long
y As Long
End Type
Private Type LVFINDINFO
flags As Long
psz As String
lParam As Long
pt As POINTAPI
vkDirection As Long
End Type
Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
'Purpose : Find/Search for an item in a listview.
'Inputs : lLvHwnd The handle to the listview.
' sItem The item to search for.
' [lFindType] The type of search to carry out (See list of "LVFI_" constants in declarations).
'Outputs : Returns the matching listitem.
Function ListviewFindItem(lLvFind As ListView, sItem As String, Optional lFindType = LVFI_PARTIAL Or LVFI_WRAP) As ListItem
Dim lItemIndex As Long, tListviewFind As LVFINDINFO
tListviewFind.flags = lFindType
tListviewFind.psz = sItem
lItemIndex = SendMessage(lLvFind.hwnd, LVM_FINDITEM, -1, tListviewFind)
If lItemIndex > -1 Then
'Return matching item
Set ListviewFindItem = lLvFind.ListItems(lItemIndex + 1)
Else
'Found nothing
Set ListviewFindItem = Nothing
End If
End Function