【问题标题】:Trying to search a column in a listview and return the result尝试在列表视图中搜索列并返回结果
【发布时间】:2012-11-26 17:39:57
【问题描述】:

我正在从指定的索引搜索我的列表视图并返回单词的第一个结果(项目所在的索引)。它工作得很好,除了我只能搜索列表视图中的第一列。如何只搜索第二列?

Private Function FindLogic(ByVal LV As ListView, ByVal CIndex As Integer, ByVal SearchFor As String) As Integer
Dim idx As Integer
Dim It = From i In LV.Items Where i.index > CIndex And i.Text = SearchFor
If It.Count > 0 Then
    idx = It(0).Index
Else
    idx = -1
End If
Return idx
End Function

【问题讨论】:

    标签: .net vb.net string visual-studio-2010 listview


    【解决方案1】:

    您需要访问 ListViewItem 的 ListViewSubItems 以获取其他列。使用子项,您将能够按索引搜索不同的列,而不仅仅是搜索文本。您可以简单地在循环中使用循环来执行搜索。如果您愿意,您可以明确表示,因为您知道您只想搜索第二列,但是通过在循环中使用循环,您实际上可以搜索任何列。这是一个示例:

    Dim idx As Integer = -1
    For Each lvi As ListViewItem In Me.lvwData.Items
        If lvi.SubItems(1).Text = "TextToSearchFor" Then
            idx = lvi.Index
        End If
    Next
    

    【讨论】:

    • 我实际上是在尝试从指定的索引中搜索并搜索第一个实例并返回它的索引。所以我可以在第 5 行开始搜索并返回指定单词的第一个实例索引。
    • 看来你还是想通了。关键是访问 SubItems 而不是 ListViewItem 的 Text 属性。
    【解决方案2】:

    我想通了。此解决方案允许您选择指定的索引开始搜索并检查索引为 1 的列。(通常是您的第二列)

        Private Function FindLogic(ByVal LV As ListView, ByVal CIndex As Integer, ByVal SearchFor As String) As Integer
        Dim idx As Integer
        Dim It = From i In LV.Items Where i.index > CIndex And i.SubItems(1).Text = SearchFor
        If It.Count > 0 Then
            idx = It(0).Index
        Else
            idx = -1
        End If
        Return idx
        End Function
    

    您还可以在函数中添加另一个参数,以便您可以选择不同的列来检查字符串,如下所示:

        Private Function FindLogic(ByVal LV As ListView, ByVal CIndex As Integer, ByVal Column As Integer, ByVal SearchFor As String) As Integer
        Dim idx As Integer
        Dim It = From i In LV.Items Where i.index > CIndex And i.SubItems(Column).Text = SearchFor
        If It.Count > 0 Then
            idx = It(0).Index
        Else
            idx = -1
        End If
        Return idx
        End Function
    

    要使用这个函数,它看起来像这样:

         FindLogic(Listview1, 1, 1, "Dog")
    

    你也可以像这样从一个选定的项目中搜索:

         FindLogic(Listview1, 1, LV.SelectedIndices(0), "Dog")
    

    【讨论】: