Tim Van Wassenhove

Passionate geek, interested in Technology. Proud father of two

16 Feb 2006

Removing selected items from a ListBox

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