所以这是我的字典:
// weapon <name, dps>
Dictionary<string, int> weapons = new Dictionary<string, int>();
weapons.Add("Chaotic Staff", 1000);
weapons.Add("Abyssal Whip", 800);
weapons.Add("Death Lotus Darts", 900);
weapons.Add("Drygore Mace", 1200);
这是我尝试将字典项添加为字符串。例如,我想在Chaotic Staff - 1000
中添加一个值作为框中的值。
var result = string.Join(", ", weapons.Select(m => m.Key + " - " + m.Value).ToArray()); //copied it from somewhere.
weaponsComboBox.DataSource = new BindingSource(result, null);
weaponsComboBox.DisplayMember = "Key";
weaponsComboBox.ValueMember = "Value"; //Argument Exception error
应该纠正什么?我对BindingSource和LINQ几乎没有理解。
答案 0 :(得分:1)
看起来你正在做两件事 - 将字典转换为字符串列表,然后尝试绑定到原始字典中的键/值对。做其中一个,但不是两个。
如果要绑定到<select multiple="multiple"></select>
并仅显示密钥:
Dictionary<string,int>
如果您想将字典转换为简单的字符串列表,则没有理由设置weaponsComboBox.DataSource = weapons;
weaponsComboBox.DisplayMember = "Key";
weaponsComboBox.ValueMember = "Value";
和DisplayMember
:
ValueMember
根据您发布的内容,我认为您不需要使用var result = weapons.Select(x => string.Format("{0} - {1}", x.Key, x.Value)).ToList();
weaponsComboBox.DataSource = result;
。