User124726
User124726

Reputation: 119

Adding Multiple Items From One Listbox to Another VB.Net

I am able to only move single items from one listbox to another with this code. I tried with both MultiSimple & MultiExtended SelectionMode.

How do I select multiple items and then move them?

Private Sub cmdAdd_Click(ByVal sender As System.Object, 
                         ByVal e As System.EventArgs
                        ) Handles cmdAdd.Click

        Dim i As Integer = Listbox1.SelectedIndex

        If i = -1 Then
            Exit Sub 'skip if no item is selected
        End If

        Listbox2.Items.Add(Listbox1.Items(i)) 
        Listbox1.Items.RemoveAt(i)

    End Sub

Upvotes: 1

Views: 25322

Answers (3)

Harsh Patel
Harsh Patel

Reputation: 1

Private Sub cmdAdd_Click(ByVal sender As System.Object, 
                     ByVal e As System.EventArgs
                    ) Handles cmdAdd.Click


For Each selectedItem In (From i In ListBox1.SelectedItems).Tolist()


    Listbox2.Items.Add(selectedItem)
    Listbox1.Items.Remove(selectedItem)

Next

End Sub

Upvotes: 0

user3426959
user3426959

Reputation: 1

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    ComboBox1.Items.Add("SanDiego")
    ComboBox1.Items.Add("BeverlyHills")
    ComboBox1.Items.Add("Florida")
    ComboBox1.Items.Add("NewYork")
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim s As String
    s = ComboBox1.SelectedItem

    ListBox1.Items.Add(s)
    ComboBox1.Items.Remove(s)
End Sub

Upvotes: 0

Tim Murphy
Tim Murphy

Reputation: 4932

You need to use SelectedIndices or SelectedItems.

Private Sub cmdAdd_Click(ByVal sender As System.Object, 
                         ByVal e As System.EventArgs
                        ) Handles cmdAdd.Click

    Dim selectedItems = (From i In ListBox1.SelectedItems).ToArray()

    For Each selectedItem In selectedItems

        Listbox2.Items.Add(selectedItem)
        Listbox1.Items.Remove(selectedItem)

    Next

End Sub

Note the use of a Linq query to get list of selected items as an array. Using an array is required to prevent "Collection changed" exceptions. You may need to add a reference to System.Linq.

Upvotes: 2

Related Questions