使用Dictionary作为数据源绑定组合框

use*_*952 59 .net c# combobox datasource winforms

我正在使用.NET 2.0,我正在尝试将组合框的数据源绑定到排序字典.

所以我得到的错误是"DataMember属性'Key'无法在数据源上找到".

        SortedDictionary<string, int> userCache = UserCache.getSortedUserValueCache();
        userListComboBox.DataSource = new BindingSource(userCache, "Key"); //This line is causing the error
        userListComboBox.DisplayMember = "Key";
        userListComboBox.ValueMember = "Value";
Run Code Online (Sandbox Code Playgroud)

Sor*_*scu 123

SortedDictionary<string, int> userCache = new SortedDictionary<string, int>
{
  {"a", 1},
  {"b", 2},
  {"c", 3}
};
comboBox1.DataSource = new BindingSource(userCache, null);
comboBox1.DisplayMember = "Key";
comboBox1.ValueMember = "Value";
Run Code Online (Sandbox Code Playgroud)

但是你为什么要设置ValueMember为"值",它不应该被绑定到"键"(以及DisplayMember"值")?

  • 你可能想要尝试的另一件事是移动行comboBox1.DataSource = new BindingSource(userCache,null); 设置DisplayMember和ValueMember后关闭 (3认同)
  • 有时,如果在 DisplayMember 之前分配 DataSource,则执行会在 DisplayMember 分配行处阻塞。对我来说,这有效——cBox.DataSource = null; cBox.DisplayMember = "值"; cBox.ValueMember = "键"; cBox.DataSource = new BindingSource(dict, null); // @dmihailescu 是对的 (2认同)

Cri*_*isS 23

我使用了Sorin Comanescu的解决方案,但在尝试获取所选值时遇到了问题.我的组合框是一个工具条组合框.我使用了"combobox"属性,它暴露了一个普通的组合框.

我曾有一个

 Dictionary<Control, string> controls = new Dictionary<Control, string>();
Run Code Online (Sandbox Code Playgroud)

绑定代码(Sorin Comanescu的解决方案 - 像魅力一样工作):

 controls.Add(pictureBox1, "Image");
 controls.Add(dgvText, "Text");
 cbFocusedControl.ComboBox.DataSource = new BindingSource(controls, null);
 cbFocusedControl.ComboBox.ValueMember = "Key";
 cbFocusedControl.ComboBox.DisplayMember = "Value";
Run Code Online (Sandbox Code Playgroud)

问题是,当我试图获取所选值时,我没有意识到如何检索它.经过几次尝试,我得到了这个:

 var control = ((KeyValuePair<Control, string>) cbFocusedControl.ComboBox.SelectedItem).Key
Run Code Online (Sandbox Code Playgroud)

希望它可以帮助别人!


小智 6

        var colors = new Dictionary < string, string > ();
        colors["10"] = "Red";
Run Code Online (Sandbox Code Playgroud)

绑定到Combobox

        comboBox1.DataSource = new BindingSource(colors, null);
        comboBox1.DisplayMember = "Value";
        comboBox1.ValueMember = "Key"; 
Run Code Online (Sandbox Code Playgroud)

Full Source ... 字典作为Combobox数据源

Jery​​y


小智 5

userListComboBox.DataSource = userCache.ToList();
userListComboBox.DisplayMember = "Key";
Run Code Online (Sandbox Code Playgroud)