如果您只想将文本变灰而不禁用它,那么以下操作将起作用:
' Purpose: If a match for <the_sText> is found, then the first item matching is moved to the top of the control, and all the other items are greyed out.
Private Sub HighlightTextInListView(ByRef the_sText As String)
Dim sKeyOfPreviousItem As String
Dim oListItemAtTop As ListItem
Dim oFoundListItem As ListItem
Dim nIndex As Long
Set oListItemAtTop = lvData.ListItems(1)
sKeyOfPreviousItem = oListItemAtTop.Tag ' We are storing the original previous item's key in the top item's Tag property.
' If it is set to non-empty string, the we know that it has been previous sorted to the top.
' Undo this before anything else.
If sKeyOfPreviousItem <> "" Then
MoveItem oListItemAtTop, lvData.ListItems.Item(sKeyOfPreviousItem).Index + 1
End If
If the_sText = "" Then
' If the search box is empty, then ungrey all the text.
SetTextForeColor vbWindowText
Else
' Look for the text.
Set oFoundListItem = lvData.FindItem(the_sText, lvwText, , lvwPartial)
If oFoundListItem Is Nothing Then
SetTextForeColor vbWindowText
Else
SetTextForeColor vbGrayText
' Find the text in the previous item to the selected item (if none, use "").
nIndex = oFoundListItem.Index
If nIndex = 1 Then
sKeyOfPreviousItem = ""
Else
sKeyOfPreviousItem = lvData.ListItems.Item(nIndex - 1).Key
End If
' Move this item to the top of the list, and set its Tag property to indicate the previous item.
' Note that this new item will not have grey text.
MoveItem(oFoundListItem, 1).Tag = sKeyOfPreviousItem
End If
End If
End Sub
' Purpose: Adds a new item to the list view.
Private Sub AddListItem(ByRef the_sKey As String, ByRef the_sDescription As String, the_sBarCode As String, ByRef the_sQuantity As String, ByRef the_sDepartment)
With lvData.ListItems
With .Add(, the_sKey, the_sDescription)
.SubItems(1) = the_sBarCode
.SubItems(2) = the_sQuantity
.SubItems(3) = the_sDepartment
End With
End With
End Sub
' Purpose: Adds a new item with the same properties as the previous, at a specific position.
Private Function MoveItem(ByRef the_oListItem As ListItem, ByVal the_nNewPos As Long) As ListItem
Dim oListItem As ListItem
Dim sKey As String
Set oListItem = lvData.ListItems.Add(the_nNewPos, , the_oListItem.Text)
oListItem.SubItems(1) = the_oListItem.SubItems(1)
oListItem.SubItems(2) = the_oListItem.SubItems(2)
oListItem.SubItems(3) = the_oListItem.SubItems(3)
sKey = the_oListItem.Key
lvData.ListItems.Remove sKey
oListItem.Key = sKey
Set MoveItem = oListItem
End Function
' Purpose: Set the fore colour of each list item.
Private Sub SetTextForeColor(ByVal the_cForeColor As OLE_COLOR)
Dim oListItem As ListItem
Dim oSubItem As ListSubItem
For Each oListItem In lvData.ListItems
oListItem.ForeColor = the_cForeColor
For Each oSubItem In oListItem.ListSubItems
oSubItem.ForeColor = the_cForeColor
Next oSubItem
Next oListItem
End Sub
当您想要运行搜索时,只需使用 HighlightTextInListView() 即可。本质上,我删除了该项目并在顶部重新添加它。为了记住它的旧位置,前一个项目的 Key 属性存储在移动项目的 Tag 属性中。要使此代码起作用,您必须为您的项目提供唯一键。