Charles Flores
Charles Flores

Reputation: 15

VB.NET ListView Questions

I have Questions? If I enter a data in a textbox, I want my listview to select the same data entered in the textbox,

example, I have a StudentNumber column in my listview and it has data on it(ex. 123456) I will enter 123456 in the textbox. The ListView must select 123456 ? Please Help

THANK YOU,

Upvotes: 1

Views: 457

Answers (1)

Matt Wilko
Matt Wilko

Reputation: 27342

I think this will do what you want. It will search the first column of the ListView for the text in the TextBox.

Setup the 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

Then in the textbox TextChanged changed event:

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

Alternatively if you want to specify which column of your ListView to search for the text then this function should do the trick:

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

Usage:

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

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

Warning - In both cases, this may cause your application to perform poorly if you have a lot of items in your listview, in that case you could consider moving the code into a background worker

Upvotes: 2

Related Questions