You need to enable JavaScript to run this app. 如何实现ListView控件所有列内容搜索 现有代码仅支持检索首列
优惠活动
大模型
产品
解决方案
定价
更多

如何实现ListView控件所有列内容搜索 现有代码仅支持检索首列

实现ListView全列检索的修改方案

问题根源

现有代码仅能检索第一列,是因为ListViewItem.Text属性默认仅对应索引为0的第一列内容,其余列的内容都存储在该Item的SubItems集合中。

修改后的检索代码

Private Sub TxtSearchLog_TextChanged(sender As Object, e As EventArgs)
    ' 提前预处理搜索关键词,避免循环中重复计算提升性能
    Dim searchKey As String = TxtSearchLog.Text.ToLower.Trim()
    Dim showitems As New List(Of ListViewItem)
    
    ' 关键词为空时直接返回所有条目,无需逐个判断
    If String.IsNullOrEmpty(searchKey) Then
        showitems.AddRange(ItemsList)
    Else
        For Each i As ListViewItem In ItemsList
            Dim isMatch As Boolean = False
            ' 遍历当前条目所有列的内容,任意一列匹配即保留该条目
            For Each subItem As ListViewItem.ListViewSubItem In i.SubItems
                If subItem.Text.ToLower.Contains(searchKey) Then
                    isMatch = True
                    Exit For ' 匹配到就提前退出内层循环,减少不必要计算
                End If
            Next
            If isMatch Then
                showitems.Add(i)
            End If
        Next
    End If
    
    ListView1.Items.Clear()
    ListView1.Items.AddRange(showitems.ToArray)
End Sub

可选优化点

  • 如果需要跳过指定列不参与检索,遍历SubItems时可以通过索引判断过滤,比如跳过第一列可写为For index = 1 To i.SubItems.Count -1,取i.SubItems(index)判断即可
  • 可以用StringComparison.OrdinalIgnoreCase替代手动转小写,写法更简洁也能避免特殊字符大小写转换的异常:
    If subItem.Text.Contains(searchKey, StringComparison.OrdinalIgnoreCase) Then
    

内容的提问来源于stack exchange,提问作者Lider13

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 16:24:02