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?
You should bind your ListBox to a
ObservableCollection<T>, by setting theserach_history.ItemsSource = myObservableCollectionThen 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.