Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind multiple ComboBox to a single List - Issue: When I choose an item, all combo boxes change

I am creating a ComboBox array dynamically and the DataSource for all the ComboBox is a single integer list that contains some integers. But when I change a value say X in any one combo box then all other combo values get reset to value X.

So here is the situation:

  • All combo box controls are bound to a single list
  • When I change selected item of a combo box, selected item of all other combo box controls also change.

How can I stop these behavior?

like image 535
Dinesh wakti Avatar asked Dec 24 '22 08:12

Dinesh wakti


1 Answers

Since you are binding all combo boxes to the same data source - a single list - they are using a single BindingManagerBase.

So when you choose an item from one of combo boxes, the current Position of the shared binding manager base changes and all combo boxes goes to that position of their shared data source.

To solve the problem you can bind them to different data source:

  • You can bind them to yourList.ToList() or any other list for example different BindingList<T>.

    combo1.DataSource = yourList.ToList();
    combo2.DataSource = yourList.ToList();
    
  • You can use different BindingSource for them and set your list as DataSource of BindingSource

    combo1.DataSource = new BindingSource { DataSource= yourList};
    combo2.DataSource = new BindingSource { DataSource= yourList};
    

Also as another option:

  • You can use different BindingContext for your combo boxes. This way even when you bind them to a single list, they are not sync anymore.

    combo1.BindingContext = new BindingContext();
    combo1.DataSource = yourList;
    combo2.BindingContext = new BindingContext();
    combo2.DataSource = yourList;
    

In fact all controls of the form use a shared BindingContext. When you bind 2 controls to a same data source, then they also use the same BindingManagerBase this way, when you for example move to next record, all controls move to next record an show value from bound property of next record. This is the same behavior that you are seeing from your combo boxes. Being sync for controls which are using the same BindingManagerBase is a desired behavior. Anyway sometimes we don't need such behavior. The post shares the reason and the solution.

like image 85
Reza Aghaei Avatar answered Jan 21 '23 09:01

Reza Aghaei