user2669068
user2669068

Reputation: 185

Remove duplicate items in the ListBox

I need to delete some items in a WPF listbox, I use this code :

while (ListBox.SelectedItems.Count > 0)
{
  ListBox.Items.Remove(ListBox.SelectedItem);
}

But the problem is that my listbox contains several same items, for example :

chocolate
milk
orange
milk
banana
apple
milk

If I select the 2nd occurence of milk at the 4th position and try to delete it with the given code, it will remove the first occurence of milk at the 2nd position (not selected) AND the selected 2nd occurence of milk at the 4th position.

I have also tried with :

while (ListBox.SelectedItems.Count > 0)
{
  ListBox.Items.RemoveAt(ListBox.Items.IndexOf(ListBox.SelectedItem));
}

But the result is the same.

Could anybody give me a clue on this ?

Upvotes: 2

Views: 1878

Answers (1)

Ehsan
Ehsan

Reputation: 32681

Try this

if (ListBox.SelectedItem != null)
{
   ListBox.Items.RemoveAt(ListBox.SelectedIndex);
}

Upvotes: 3

Related Questions