So here is my dictionary:
// 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);
Here is my attempt to add my dictionary items as a string. For example I want to add in Chaotic Staff - 1000
as one of the values in the box.
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
What should be the correction? I have little to no understanding on BindingSource and LINQ.
It looks like you're doing two things - converting your dictionary to a list of strings, but then trying to bind to the key/value pair from the original dictionary. Do one or the other, but not both.
If you want to bind to the Dictionary<string,int>
and display only the key:
weaponsComboBox.DataSource = weapons;
weaponsComboBox.DisplayMember = "Key";
weaponsComboBox.ValueMember = "Value";
If you want to convert the dictionary to a simple list of strings, then there's no reason to set the DisplayMember
and ValueMember
:
var result = weapons.Select(x => string.Format("{0} - {1}", x.Key, x.Value)).ToList();
weaponsComboBox.DataSource = result;
From what you've posted, I don't think you need to use a BindingSource
either.