VB.NET ListBox - Transfer Items Between 2 ListBoxes

July 12, 2017 Oclemy VB.NET ListBox 1 minute, 6 seconds

This is a simple play with two listboxes.We select a single item in a listbox and transfer it to the next listbox on button click.We can transfer in both directions.

Public Class Form1

    Private Sub MoveRight()
        'CHECK IF USER HAS SELECTED
        If ListBox1.SelectedIndex = -1 Then
            MsgBox("Nothing to Move !!")

        Else
            'TO HOLD ALL SELECTED ITEMS
            Dim selected As New ArrayList()

            'ADD SELECTED
            For Each item In ListBox1.SelectedItems
                selected.Add(item)
            Next

            'THEN MOVE SELECTED ITEMS TO RIGHT
            For Each item In selected
                ListBox2.Items.Add(item)
            Next

            'THEN REMOVE THEM FROM LEFT
            For Each item In selected
                ListBox1.Items.Remove(item)
            Next

        End If
    End Sub

    Private Sub MoveLeft()
        'CHECK IF USER HAS SELECTED
        If ListBox2.SelectedIndex = -1 Then
            MsgBox("Nothing to Move !!")

        Else
            'TO HOLD ALL SELECTED ITEMS
            Dim selected As New ArrayList()

            'ADD SELECTED
            For Each item In ListBox2.SelectedItems
                selected.Add(item)
            Next

            'THEN MOVE SELECTED ITEMS TO LEFT
            For Each item In selected
                ListBox1.Items.Add(item)
            Next

            'THEN REMOVE THEM FROM RIGHT
            For Each item In selected
                ListBox2.Items.Remove(item)
            Next

        End If
    End Sub

    Private Sub rightBtn_Click(sender As Object, e As EventArgs) Handles rightBtn.Click
        MoveRight()
    End Sub

    Private Sub leftBtn_Click(sender As Object, e As EventArgs) Handles leftBtn.Click
        MoveLeft()
    End Sub
End Class

Best Regards.

Comments