Today i was experimenting with a couple of windows controls. For some reason i wasn’t able to remove the selected items from a ListBox. Here is the code that didn’t work:
For Each index As Integer = ListBox1.SelectedIndices ListBox2.Items.Add(ListBox1.Items(index)) ListBox1.Items.Remove(index) End For
The problem is that when you remove an item from the collection the indices change. Here is a possible solution:
Dim index As Integer = ListBox1.SelectedIndex While index <> -1 ListBox2.Items.Add(ListBox1.Items(index)) ListBox1.Items.Remove(index) index = ListBox1.SelectedIndex End While
excellent – only real working example googled up to now! Modified it to c# and it works!
Here’s an alternative that worked for me:
For i As Integer = (videosListBox.SelectedItems.Count – 1) To 0 Step -1
videosListBox.Items.Remove(videosListBox.SelectedItems(i))
Next