将多个项目从一个列表框添加到另一个 VB.Net
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6664890/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding Multiple Items From One Listbox to Another VB.Net
提问by User124726
I am able to only move single items from one listbox to another with this code. I tried with both MultiSimple & MultiExtended SelectionMode.
我只能使用此代码将单个项目从一个列表框移动到另一个列表框。我尝试了 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
回答by Tim Murphy
You need to use SelectedIndices or SelectedItems.
您需要使用 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
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.
请注意使用 Linq 查询以数组形式获取所选项目的列表。需要使用数组来防止“集合已更改”异常。您可能需要添加对 System.Linq 的引用。
回答by user3426959
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
回答by Harsh Patel
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