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

This entry was posted on Thursday, February 16th, 2006 at 02:53 and is filed under Visual Basic, Windows Forms. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.

2 Responses to “Removing selected items from a ListBox”

  1. Helga says:

    excellent – only real working example googled up to now! Modified it to c# and it works!

  2. John W says:

    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