c# 使用Dictionary作為數據源綁定組合框
4
Answers
我使用了Sorin Comanescu的解決方案,但在嘗試獲取所選值時遇到了問題。 我的組合框是一個工具條組合框。 我使用了“combobox”屬性,它暴露了一個普通的組合框。
我曾有一個
Dictionary<Control, string> controls = new Dictionary<Control, string>();
綁定代碼(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";
問題是,當我試圖獲取所選值時,我沒有意識到如何檢索它。 經過多次嘗試,我得到了這個:
var control = ((KeyValuePair<Control, string>) cbFocusedControl.ComboBox.SelectedItem).Key
希望它可以幫助別人!
c# .net winforms combobox datasource
我正在使用.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";
54 votes
c#
userListComboBox.DataSource = userCache.ToList();
userListComboBox.DisplayMember = "Key";
c#1
52
如果這不起作用,為什麼不簡單地在字典上做一個foreach循環,將所有項目添加到組合框中?
foreach(var item in userCache)
{
userListComboBox.Items.Add(new ListItem(item.Key, item.Value));
}
c#2
51
試著這樣做....
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";
}
c#3
50