Ameen
Ameen

Reputation: 1907

Remove item from listbox

I am trying to remove an item from a listbox using C# code using the following line of code:

search_history.Items.RemoveAt(selected);

However I get the following message: Operation not supported on read-only collection.

What is the workaround solution for this problem other than resetting the listbox and entering the items all over again?

Upvotes: 0

Views: 1234

Answers (3)

ellic
ellic

Reputation: 798

Item of the itemsource should implement the INotifyCollectionChanged interface. To simplify matters, you can use the ObservableCollection< T > instead of the List< T >. Then using the code shown below will work well:

(yourlistbox.ItemsSource as ObservableCollection<T>).RemoveAt(selected);

Hope that helps.

Upvotes: 0

Claus J&#248;rgensen
Claus J&#248;rgensen

Reputation: 26344

You should bind your ListBox to a ObservableCollection<T>, by setting the serach_history.ItemsSource = myObservableCollection

Then you can do myObservableCollection.Remove(search_history.SelectedItem) and the item will be removed from the collection, and the UI will update accordingly.

In general, you should always aim to use Data Bindings rather than add items directly to a collection.

Upvotes: 2

James
James

Reputation: 1

search_history.Items.Remove(search_history.SelectedItem);

Upvotes: 0

Related Questions