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

后端 未结 1 1543
悲&欢浪女
悲&欢浪女 2020-11-27 22:51

I am creating a ComboBox array dynamically and the DataSource for all the ComboBox is a single integer list that contains some integer

相关标签:
1条回答
  • 2020-11-27 23:43

    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.

    0 讨论(0)
提交回复
热议问题