Sturm
Sturm

Reputation: 4125

Can't remove items from comboBox c#

I have a

public ObservableCollection<Canal> channelList { get; set; }

(I also tried a List, Canal is a class). I plot some data from List that are inside the channels. And I also have a comboBox displaying each channel name.

My problem is that I can't do this:

comboBox1.Items.Clear();

Because it gives me "Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead." error.

The data is binded but I don't know if that's important. Thanks

Upvotes: 2

Views: 3929

Answers (2)

Clemens
Clemens

Reputation: 128060

Unless you want to remove the binding (as suggested by the other answer), you would have to clear the collection that is the source of the binding:

channelList.Clear();

You can now add new items to channelList, which will update the ComboBox, as the binding is still intact.

Upvotes: 1

morpil
morpil

Reputation: 121

In MSDN page, it says:

When ItemsSource is in use, setting the property to null removes the collection and restores usage to Items, which will be an empty ItemCollection.

Because ItemsSource is in use, you have to set it to null to clear items:

comboBox1.ItemsSource = null;

Upvotes: 4

Related Questions