VB.NET Listview Textchanged搜索

时间:2012-12-19 18:12:57

标签: vb.net listview search filter textchanged

我已经尝试在stackoverflow上搜索并实现我找到的代码,但无济于事。随着文本的更改,我想使用文本框中的当前文本来过滤listview项(因此未关闭以匹配的项目将被删除)并且它只留下列中包含的任何内容。

这是我的意思的一个例子:

搜索:“乔治”

| 1 |安德森席尔瓦|安德森席尔瓦是... |

的冠军

| 2 | 乔治 St-Pierre | Georges 是... |

的冠军

| 3 | Georges Sotoropolis | Georges Sotoropolis是轻量级部门的战士|

使用此搜索,仅返回第2行和第3行。第一行将被省略而不显示。擦除条款后,它就会显示出来。

以下是我目前的代码:

Private Sub tbSearch_TextChanged(sender As Object, e As System.EventArgs) Handles tbSearch.TextChanged
    lwArticles.BeginUpdate()

    If tbSearch.Text.Trim().Length = 0 Then
        'Clear listview
        lwArticles.Clear()

        'If nothing is in the textbox make all items appear
        For Each item In originalListItems
            lwArticles.Items.Add(item)
        Next
    Else
        'Clear listview
        lwArticles.Clear()

        'Go through each item in the original list and only add the ones which contain the search text
        For Each item In originalListItems
            If item.Text.Contains(tbSearch.Text) Then
                lwArticles.Items.Add(item)
            End If
        Next
    End If
    lwArticles.EndUpdate()

End Sub

它似乎正在工作,但一旦我在tbSearch中输入内容,我就看不到listview项目了。滚动条变得更小/更大,这取决于由于正在执行搜索而存在更多/更少的项目。我的问题似乎是不可见的

谢谢!

3 个答案:

答案 0 :(得分:2)

Listview.Clear会清除项目,列和组。您似乎只想清除这些项目,因此请拨打lwArticles.Items.Clear而不是lwArticles.Clear

答案 1 :(得分:2)

我建议采用另一种方法 - 首先根据原始项目创建DataTable。然后创建DataView并将其指定为DataSource的{​​{1}}。现在您可以更改DataView.RowFilter,您的列表会自动更新,因此只会显示与过滤器匹配的项目。使用这种方法,您不需要每次都从头开始重新创建所有内容,并且ListView变得非常简单和可维护 - 如果已经创建了相应的TextChanged,它只会更改RowFilter

答案 2 :(得分:1)

以下是我的问题的最终答案:

Private originalListItems As New List(Of ListViewItem) 'this gets populated on form load

Private Sub tbSearch_TextChanged(sender As Object, e As System.EventArgs) Handles tbSearch.TextChanged
    lwArticles.BeginUpdate()

    If tbSearch.Text.Trim().Length = 0 Then
        'Clear listview
        lwArticles.Items.Clear()

        'If nothing is in the textbox make all items appear
        For Each item In originalListItems
            lwArticles.Items.Add(item)
        Next
    Else
        'Clear listview
        lwArticles.Items.Clear()

        'Go through each item in the original list and only add the ones which contain the search text
        For Each item In originalListItems
            If item.Text.Contains(tbSearch.Text) Then
                lwArticles.Items.Add(item)
            End If
        Next
    End If

    lwArticles.EndUpdate()
End Sub

对Dan-o的解释是,lwArticles.Clear()将清除所有内容。他告诉我,我需要lwArticles.Items.Clear()来清除listview中的项目。