WinForms多ComboBox数据绑定异常:选中项联动变更问题
问题原因
所有ComboBox共享了同一个数据源实例KeyBoardConst.AVAILABLE_KEYS,WinForms中ListControl(ComboBox继承自该类)会自动使用**相同的CurrencyManager**管理数据源的当前选中项,导致任意一个控件的选中项变更时,其他绑定同一数据源的控件会同步跟随变化。
解决方案
给每个ComboBox分配独立的数据源副本,确保每个控件拥有专属的CurrencyManager,彻底切断选中项的联动关系。
修改后的代码示例
for (int i = 0; i < 12; i++) { var item = new Item() { Index = i + 1, SelectedCode = 100 }; string selectName = "keySelect" + (i + 1); Control found = groupBox1.Controls.Find(selectName, true).FirstOrDefault(); if (found != null && found is ComboBox keySelect) { // 为每个ComboBox创建数据源的独立副本,替换YourKeyType为实际元素类型 keySelect.DataSource = new List<YourKeyType>(KeyBoardConst.AVAILABLE_KEYS); keySelect.DisplayMember = "text"; keySelect.ValueMember = "value"; keySelect.SelectedIndex = 0; keySelect.DataBindings.Add("SelectedValue", item, "SelectedCode"); } }
补充说明
- 把
YourKeyType替换成KeyBoardConst.AVAILABLE_KEYS实际的元素类型(比如自定义的KeyItem类)。 - 如果
AVAILABLE_KEYS是数组类型,使用KeyBoardConst.AVAILABLE_KEYS.ToArray()创建新数组副本也能达到同样效果。 - 若需要数据源支持动态更新,可改用
BindingList<YourKeyType>包装数据源,既保留独立副本特性,又能支持数据变更通知。
内容的提问来源于stack exchange,提问作者muk
相关产品推荐
相关产品推荐

