我正在尝试创建一个循环,每当我点击搜索按钮并将列表框聚焦到匹配的文本时,它将通过子项读取 ListView 上的信息,以查找与文本框中的文本匹配的文本。下面是我所拥有的,但它一直告诉我字符串的值无法转换。我也很确定我的数字不会正确循环,但我不太确定如何使它们无限循环直到语句结束。
Dim T As String
T = Lines.Text
For r As Integer = 0 to -1
For C As Integer = 0 to -1
If List.Items(r).SubItems(C).Text = Lines.Text Then
List.FocusedItem = T
End If
Next
Next
End Sub
我不明白你的代码,但我明白这个问题。下面是搜索列表视图的所有行和列的示例代码。搜索不区分大小写,并支持“查找下一个匹配项”场景。如果在任何列中找到匹配或部分匹配,则选择该行。 TextBox1 获取要查找的文本。 FindBtn 开始新的搜索。
Private SrchParameter As String = ""
Private NxtStrtRow As Integer = 0
Private Sub FindBtn_Click(sender As Object, e As EventArgs) Handles FindBtn.Click
If Not String.IsNullOrWhiteSpace(TextBox1.Text) Then
SrchParameter = TextBox1.Text
NxtStrtRow = 0
SearchListView()
End If
End Sub
Private Sub ListView1_KeyDown(sender As Object, e As KeyEventArgs) Handles ListView1.KeyDown
If e.KeyCode = Keys.F3 Then
SearchListView()
End If
End Sub
Private Sub SearchListView()
' selects the row containing data matching the text parameter
' sets NxtStrtRow (a form level variable) value for a "find next match" scenario (press F3 key)
If ListView1.Items.Count > 0 Then
If SrchParameter <> "" Then
Dim thisRow As Integer = -1
For x As Integer = NxtStrtRow To ListView1.Items.Count - 1 ' each row
For y As Integer = 0 To ListView1.Columns.Count - 1 ' each column
If InStr(1, ListView1.Items(x).SubItems(y).Text.ToLower, SrchParameter.ToLower) > 0 Then
thisRow = x
NxtStrtRow = x + 1
Exit For
End If
Next
If thisRow > -1 Then Exit For
Next
If thisRow = -1 Then
MsgBox("Not found.")
NxtStrtRow = 0
TextBox1.SelectAll()
TextBox1.Select()
Else
' select the row, ensure its visible and set focus into the listview
ListView1.Items(thisRow).Selected = True
ListView1.Items(thisRow).EnsureVisible()
ListView1.Select()
End If
End If
End If
End Sub
不要像在 ListView 中那样循环,而是尝试使用 For Each 来代替:
searchstring as String = "test1b"
ListView1.SelectedIndices.Clear()
For Each lvi As ListViewItem In ListView1.Items
For Each lvisub As ListViewItem.ListViewSubItem In lvi.SubItems
If lvisub.Text = searchstring Then
ListView1.SelectedIndices.Add(lvi.Index)
Exit For
End If
Next
Next
ListView1.Focus()
这将选择子项目中具有文本匹配的每个项目。 不要将此代码放入表单加载处理程序中,它不会将焦点提供给列表视图,并且不会显示所选项目。请改用按钮单击处理程序。
这是在 vb net 中的列表视图和组合框控件中搜索的最简单方法
dim i as integer = cb_name.findstring(tb_name.text) 'findstring will return index
if i = -1 then
msgbox("Not found")
else
msgbox("Item found")
end if
只是为了更新此线程...
现在您可以将
ListView.FindItemWithText(<text to find>)
用作 Microsoft .Net,它返回一个 ListViewItem 对象,如果未找到则返回 Nothing。