将一个列表框中的多个项添加到另一个列表框中

时间:2011-07-12 13:26:04

标签: vb.net visual-studio-2010

我只能使用此代码将单个项目从一个列表框移动到另一个列表框。我尝试使用MultiSimple和amp; MultiExtended SelectionMode。

如何选择多个项目然后移动它们?

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

3 个答案:

答案 0 :(得分:2)

您需要使用SelectedIndices或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

请注意使用Linq查询将所选项目列表作为数组。需要使用数组来防止“收集已更改”异常。您可能需要添加对System.Linq的引用。

答案 1 :(得分:0)

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

答案 2 :(得分:0)

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