2012-01-16 109 views
1

我有疑問? 如果我在一個文本框中輸入一個數據, 我希望我的ListView選擇在文本框中輸入了相同的數據,VB.NET ListView問題

例如, 我在我的列表視圖有StudentNumber列,它有它(例如數據123456 ) 我將在文本框中輸入123456。 ListView必須選擇123456? 請幫助

謝謝

回答

2

我認爲這會做你想要什麼。它將搜索文本框中文本的ListView的第一個列。

設置列表視圖:

With ListView1 
    .MultiSelect = False 'Ensure only one item selected at a time 
    .HideSelection = False 'Shows the selection when the textbox changes 
    'Add some items for testing 
    .Items.Add("1234") 
    .Items.Add("1122") 
    .Items.Add("1133") 
End With 

然後在文本框中TextChanged更改事件:

Private Sub TextBox1_TextChanged(sender As System.Object, e As System.EventArgs) Handles TextBox1.TextChanged 
    ListView1.SelectedItems.Clear() 
    Dim foundItem As ListViewItem = ListView1.FindItemWithText(TextBox1.Text, False, 0, False) 
    If (foundItem IsNot Nothing) Then foundItem.Selected = True 
End Sub 

另外,如果你想指定要搜索的你的ListView列的文本,則這功能應該訣竅:

Private Sub SelectListViewItem(ByRef listviewSource As ListView, ByVal textToFind As String, ByVal column As Integer) 
    Dim foundItem As ListViewItem = Nothing 
    Dim startIndex As Integer = 0 

    listviewSource.SelectedItems.Clear() 

    Do Until Not foundItem Is Nothing AndAlso foundItem.SubItems(column).Text = TextBox2.Text 
     If foundItem Is Nothing Then startIndex = 0 Else startIndex = foundItem.Index + 1 
     If startIndex > listviewSource.Items.Count - 1 Then Exit Sub 'We have reached end of the listview 
     foundItem = listviewSource.FindItemWithText(textToFind, True, startIndex) 
     If foundItem Is Nothing Then Exit Sub 
    Loop 

    If (foundItem IsNot Nothing) Then foundItem.Selected = True 
End Sub 

用法:

Private Sub TextBox2_TextChanged(sender As System.Object, e As System.EventArgs) Handles TextBox2.TextChanged 

    SelectListViewItem(ListView1, TextBox2.Text, 1) 
End Sub 

警告 - 在這兩種情況下,這可能會導致如果你有很多的項目的應用程序表現不佳在您的列表視圖,在這種情況下,你可以考慮代碼移動到背景工作人員

+0

非常感謝您的先生,我有另一個問題,如果我想要項目點擊,而不是選擇?謝謝 – 2012-01-19 14:13:52