简体   繁体   中英

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?

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!

This works sufficiently. Not sure about the performance on very large lists, but you probably don't want a huge ComboBox list either.

foreach (var item in myDic)
    comboBox1.Items.Add(item.Value); // Populate the ComboBox by manually adding instead of binding

comboBox1.SelectedIndex = comboBox1.Items.IndexOf(myDic[1037]);

The clear issue with this code is the dismissal of the DataSource Binding, which may or may not be okay with you. Perhaps someone else will provide a better answer.

Yesterday looking for, I happened to inquire driving the DataSource, it casts it to BindingSource and discovered that a property "Current" which determines that KeyPar is selected internally from the link. So change the values to test and Bingo !

Dictionary<int,string> diccionario=new Dictionary<int,string>();
diccionario.Add(1,"Bella");
diccionario.Add(2,"Bestia");
this.comboList.DisplayMember = "Value";
this.comboList.ValueMember = "Key";    
this.comboList.DataSource = new BindingSource(diccionario, null);
((BindingSource)this.comboList.DataSource).Position=0; // select init

///////Method's change ///////

((BindingSource)this.comboList.DataSource).Position =Convert.ToInt32(value);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM