具有组合框字典的参数异常

本文关键字:参数 异常 字典 组合 | 更新日期: 2023-09-27 18:33:04

这是我的字典:

// 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 知之甚少。

具有组合框字典的参数异常

看起来您正在做两件事 - 将字典转换为字符串列表,然后尝试绑定到原始字典中的键/值对。做一个或另一个,但不能同时做两个。

如果要绑定到Dictionary<string,int>并仅显示密钥:

weaponsComboBox.DataSource = weapons;
weaponsComboBox.DisplayMember = "Key";
weaponsComboBox.ValueMember = "Value";

如果要将字典转换为简单的字符串列表,则没有理由设置DisplayMemberValueMember

var result = weapons.Select(x => string.Format("{0} - {1}", x.Key, x.Value)).ToList();
weaponsComboBox.DataSource = result;

从您发布的内容来看,我认为您也不需要使用BindingSource