使用字典作为数据源绑定Combobox

我正在使用.NET 2.0,我试图将一个combobox的数据源绑定到一个已sorting的字典。

所以我得到的错误是“数据源属性”键“找不到数据源”。

SortedDictionary<string, int> userCache = UserCache.getSortedUserValueCache(); userListComboBox.DataSource = new BindingSource(userCache, "Key"); //This line is causing the error userListComboBox.DisplayMember = "Key"; userListComboBox.ValueMember = "Value"; 
 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"; 

但是,为什么你将ValueMember设置为“Value”,不应该将它绑定到“Key”(并且DisplayMember “Value”)?

我用Sorin Comanescu的解决scheme,但试图获得选定的价值时遇到问题。 我的combobox是一个工具栏combobox。 我使用了“combobox”属性,这暴露了一个正常的combobox。

我曾有一个

  Dictionary<Control, string> controls = new Dictionary<Control, string>(); 

绑定代码(Sorin Comanescu的解决scheme – 像魅力一样工作):

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

问题是,当我试图获得选定的价值,我不知道如何检索它。 经过几次尝试,我得到了这个:

  var control = ((KeyValuePair<Control, string>) cbFocusedControl.ComboBox.SelectedItem).Key 

希望它能帮助别人!

  var colors = new Dictionary < string, string > (); colors["10"] = "Red"; 

绑定到Combobox

  comboBox1.DataSource = new BindingSource(colors, null); comboBox1.DisplayMember = "Value"; comboBox1.ValueMember = "Key"; 

Full Source … 字典作为combobox数据源

Jery​​y

 userListComboBox.DataSource = userCache.ToList(); userListComboBox.DisplayMember = "Key"; 

字典不能直接用作数据源,你应该做的更多。

 SortedDictionary<string, int> userCache = UserCache.getSortedUserValueCache(); KeyValuePair<string, int> [] ar= new KeyValuePair<string,int>[userCache.Count]; userCache.CopyTo(ar, 0); comboBox1.DataSource = ar; new BindingSource(ar, "Key"); //This line is causing the error comboBox1.DisplayMember = "Value"; comboBox1.ValueMember = "Key"; 

如果这不起作用,为什么不简单地做一个foreach循环遍历字典添加到combobox的所有项目?

 foreach(var item in userCache) { userListComboBox.Items.Add(new ListItem(item.Key, item.Value)); } 

使用 – >

 comboBox1.DataSource = colors.ToList(); 

除非字典转换为列表,否则combobox无法识别其成员。

试试像这样做….

 SortedDictionary<string, int> userCache = UserCache.getSortedUserValueCache(); // Add this code if(userCache != null) { userListComboBox.DataSource = new BindingSource(userCache, null); // Key => null userListComboBox.DisplayMember = "Key"; userListComboBox.ValueMember = "Value"; }