Search code examples
vb.netlistboxselecteditems

Programmatically select items in listbox with value's from list


Orignal question: I made a search function for a listbox. If i search for a value; the listbox clears all items, and executes a items.add function (which contains the given values from the textbox). I want to "save" the selected values in listbox4 (listbox5 are also the selected items). I tried to use the setselected function, but this function doesn't allow strings. Is there a workaround which saves the selected items?

Update:

Thanks, I implemented your snippet.

Below is my the code (work in progress). It add's multiple values of the same value in listbox4. Besides the selected value (just one added) it add's the same value unselected. Beside this issue the code works.

Does anyone have an idea?

Private Sub TextBox1_TextChanged(sender As System.Object, e As System.EventArgs) Handles TextBox1.TextChanged

    Dim selected As Object()
    selected = (From selitem In ListBox5.SelectedItems Select selitem).ToArray()

    ListBox4.Items.Clear()

    For Each item In ListBox3.Items
        If item.contains(TextBox1.Text) Then
            ListBox4.Items.Add(item)
        End If
    Next

    For Each item In ListBox5.Items
        If item.contains(TextBox1.Text) Then
            ListBox4.Items.AddRange(selected)
            Array.ForEach(selected, Sub(selitem As Object) ListBox4.SelectedItems.Add(selitem))
        End If
    Next
End Sub

Private Sub ListBox4_Click(sender As Object, e As System.EventArgs) Handles ListBox4.Click

    Dim additems As String
    For Each additems In ListBox4.SelectedItems
        ListBox5.Items.Add(additems)
    Next

    ''REMOVE DUPLICATES
    Dim List As New ArrayList
    For Each item1 As String In ListBox5.Items
        If Not List.Contains(item1) Then
            List.Add(item1)
        End If
    Next
    ListBox5.Items.Clear()
    For Each item2 As String In List
        ListBox5.Items.Add(item2)
    Next

    Dim i As Integer
    For i = 0 To Me.ListBox5.Items.Count - 1
        Me.ListBox5.SetSelected(i, True)
    Next
End Sub

Solution

  • I'm not sure how all your listboxes interact with each other so this is a "conceptual example" of how to add and select (selected) items from one listbox to another.

    Lets assume you have two listboxes: source and target. First store all selected items from the source listbox into an array.

    Dim selected As Object() = (From item In Me.sourceListBox.SelectedItems Select item).ToArray()
    

    Now, it's safe to to whatever we want with the items in the source listbox.

    Me.sourceListBox.Items.Clear()
    

    Next, we'll add all the items to the target listbox.

    Me.targetListBox.Items.AddRange(selected)
    

    Finally, we add all items to the SelectedItems collection.

    Array.ForEach(selected, Sub(item As Object) Me.targetListBox.SelectedItems.Add(item))