I was writing a Windows Application and I had a very simple need: Remove all Selected items from a ListBox control. If you have tried to simple use code like the one below:
foreach
(
int
selectedIndex
in
myListBox.SelectedIndices)
{
myListBox.Items.RemoveAt(selectedIndex);
}
You know it wouldn't work, because as soon as you remve the first selected index, your ListBox.Items array has changed indecies as a result of the first removal. So I Googled arround for some quick code to copy, and was surprised after opening the first 6-7 search results that none had the answer to my need, so I wrote my own code... here it is:
while (myListBox.SelectedItems.Count > 0)
{
myListBox.Items.Remove(myListBox.SelectedItems[0]);
}
This should take care of the problem.