Guapo Guapo - 3 months ago 14
C# Question

How can I change my current selected item by either the key or value of my datasource?

I have a

Dictionary<uint, string>
and a
ComboBox
using the style
DropDownList
, where I bind this dictionary, like:

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


Now I would like to be able to select an arbitrary item of my dictionary with a button click, so given the bound dictionary items:

Dictionary<uint, string> myDic = new Dictionary<uint, string>()
{
{ 270, "Name1" },
{ 1037, "Name2" },
{ 1515, "Name3" },
};


I have tried:

comboBox1.SelectedItem = myDic[270];
comboBox1.SelectedText = myDic[270];
comboBox1.SelectedValue = myDic[270];
comboBox1.SelectedItem = 270;
comboBox1.SelectedValue = 270;


But none of the above changed the selected item.

How can I change my current selected item by either the key or value of my datasource?

Answer

You can do it with a little extension method I found here

Just put this into an extension class.

public static KeyValuePair<TKey, TValue> GetEntry<TKey, TValue>
        (this IDictionary<TKey, TValue> dictionary,
            TKey key)
{
    return new KeyValuePair<TKey, TValue>(key, dictionary[key]);
}

And then you can just set your item like this

comboBox1.SelectedItem = myDic.GetEntry<uint,string>(1515);

The key to this problem is that you have to set the KeyValuePair (and not just the uint or string value/key).

Hope this helps!