dag623 dag623 - 4 months ago 41
C# Question

WinForms Combobox not Removing Item

I am writing a WinForms app for school in which a user is shown a flag and must choose the appropriate country from a comboBox. I am using a List of type Flag as the DataSource for the comboBox...

List<Flag> flags;
comboBox.DataSource = flags;

After a turn, I am removing the previous flag from the list and updating the comboBox DataSource...

comboBox.DataSource = flags;

I am finding that the flag is being removed from the list but not from the comboBox. Where am I going wrong?


Root problem here is that the ComboBox is not receiving any kind of notifications when its datasource changes, so obviously it doesn't refreshes visually as it should, because it doesn't realises anything has happened.

The less-than-ideal solution is what Sajeetharan suggested, to remove the list althogether and add it again. This forces the control to reread the whole list again and so it "catches" the change, removing the now missing item.

A better solution is to use a proper collection type that provides change notifications to the control and allows it to redraw as needed. That's the purpose of the BindingList<T> class. It's often advised to use this when setting data sources for bindings instead of plain lists.

So in short, your code would become:

BindingList<Flag> flags = new BindingList<Flag>();
comboBox.DataSource = flags;

Afterwards, you simply remove an item from it:


And the data binding engine takes care of deleting the item from the combo.