在我的Listview中有4列,还有一个TextBox。如何让用户在Listview的第二列中搜索字符串?
答案 0 :(得分:0)
Private Function getListItemByName(query As String) As ListViewItem
For Each lvi As ListViewItem In lst.Items
If lvi.Text.Equals(query) Then Return lvi
For Each si As ListViewItem.ListViewSubItem In lvi.SubItems
If si.Text.Equals(query) Then Return lvi
Next
Next
Return Nothing
End Function
http://www.dreamincode.net/forums/topic/237883-search-for-an-item-in-listview/
答案 1 :(得分:0)
一种方法是使用LINQ:
Public Function SearchLV(lv As ListView, SearchString As String, Colmn As Integer) As List(Of ListViewItem)
SearchLV = (From item In lv.Items.OfType(Of ListViewItem)()
Where item.SubItems(Colmn).Text = SearchString
Select item).ToList
If SearchLV.Count = 0 Then
SearchLV.Add(New ListViewItem("Your search returned no results"))
End If
End Function
此函数将返回与特定列中的搜索词匹配的列表视图项列表。 colmn参数是列的基于零的索引。如果未找到任何项目,则列表中的第一项将包含该消息。
检索项只是遍历列表:
Private Sub btnSearch_Click(sender As System.Object, e As System.EventArgs) Handles btnSearch.Click
Dim searchstring As String = TextBox1.Text
Dim searchlist As List(Of ListViewItem) = Search(ListView1, searchstring, 2)
Dim mssage As String = ""
For Each item In searchlist
For Each subitem As ListViewItem.ListViewSubItem In item.SubItems
mssage += subitem.Text + "-"
Next
mssage = mssage.Substring(0, mssage.Length - 1) + vbNewLine
Next
MessageBox.Show(mssage)
End Sub
如果您想要部分单词搜索更改:
Where item.SubItems(Colmn).Text = SearchString
为:
Where item.SubItems(Colmn).Text.Contains(SearchString)
答案 2 :(得分:0)
这对我有用,易于理解且易于修改。 有了这个,你可以在listview中搜索指定的行。
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
For Each info As ListViewItem In ListView1.Items
Dim NameCheck As String = 0
Dim SurnameCheck As String = 0
Dim IDCheck As String = 0
NameCheck = info.Text
SurnameCheck = info.SubItems(1).Text
IDCheck = info.SubItems(2).Text
If NameCheck = TextBox1.Text Then
If SurnameCheck = TextBox2.Text Then
If IDCheck = TextBox3.Text Then
MessageBox.Show("User is already in database!!!", "Invalid Input", MessageBoxButtons.OK, MessageBoxIcon.Warning)
GoTo ErrorReturn 'execute difference piece of code
End If
End If
End If
Next