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
  1. excellent – only real working example googled up to now! Modified it to c# and it works!

  2. 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

  3. @John W: That’s an elegant solution !! Thank you !

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>