相同的字符串列表数据绑定造成ComboBox控件的奇怪行为字符串、绑定、控件、奇怪

2023-09-03 06:52:10 作者:相忘于江湖

我有绑定到字符串相同的列表中有两个组合框的数据:

I have two comboboxes data binded to the same list of strings:

cbo1.DataSource    = niches_list.LIST_niches;
cbo1.DisplayMember = "LIST_niches";             
cbo2.DataSource    = niches_list.LIST_niches;
cbo2.DisplayMember = "LIST_niches";         

这一切都加载好​​,但是当我改变cbo1的选择项目,然后cbo2更改选择也;相反认为:如果我的cbo1变化cbo2所选项目的选择的项目改变为相同的索引。为什么是这样?有没有解决?

It all loads well but when I change the selected item of cbo1 then cbo2 changes the selection also; the reverse holds: if I change the selected item of cbo2 the selected item of cbo1 changes to the same index. Why is this? Is there a fix?

推荐答案

使用的 BindingSource的以保持两个组合框货币管理不同的

Use a BindingSource to keep the two comboboxes currency management distinct

BindingSource bs = new BindingSource();
bs.DataSource = niches_list.LIST_niches
cbo1.DisplayMember = "LIST_niches";             
cbo1.DataSource = bs;

BindingSource bs2 = new BindingSource();
bs2.DataSource = niches_list.LIST_niches;
cbo2.DisplayMember = "LIST_niches";             
cbo2.DataSource = bs2;

A 的BindingSource 对象作为链接类文档解释了许多功能。在你的情况下,重要的是货币管理这意味着它处理代其客户端(组合框)中在基础数据源的当前位置。该 BindingSource.Current 的属性是在两个实例之间的不同,这是关键保持两个组合框选择的项目分开。

A BindingSource object has many functionality as explained in the link to the class documentation. In your case the important one is the currency management meaning that it handles the current position over the underlying data source in behalf of its client (the combobox). The BindingSource.Current property is different between the two instances and this is the key to keep the two comboboxes selected item separated.