Setting selected item in combobox bound to dictionary

无人久伴 提交于 2019-12-14 03:51:42

问题


I have a combobox that is bound to a dictionary like this:

Dictionary<int, string> comboboxValues = new Dictionary<int, string>();
comboboxValues.Add(30000, "30 seconds");
comboboxValues.Add(45000, "45 seconds");
comboboxValues.Add(60000, "1 minute");
comboBox1.DataSource = new BindingSource(comboboxValues , null);
comboBox1.DisplayMember = "Value";
comboBox1.ValueMember = "Key";

I'm getting the key from the SelectedItem like this:

int selection = ((KeyValuePair<int, string>)comboBox1.SelectedItem).Key;

So if my user chooses the "45 seconds" option, I get back 45000 and save that value to an XML file. When my application is loaded, I need to read that value and then automatically set the combobox to match. Is it possible to do this when I only the key of 45000? Or do I need to save the value ("45 seconds") to the file instead of the key?


回答1:


Yes you could use just the 45000

comboBox1.SelectedItem = comboboxValues[45000];

If you know the index then you can use

comboBox1.SelectedIndex = i;

i is zero based and -1 means no selection.

Or set the SelectedItem

comboBox1.SelectedItem = new KeyValuePair<int, string>(45000, "45 seconds");

private void Form1_Load(object sender, EventArgs e)
{
    Dictionary<int, string> comboboxValues = new Dictionary<int, string>();
    comboboxValues.Add(30000, "30 seconds");
    comboboxValues.Add(45000, "45 seconds");
    comboboxValues.Add(60000, "1 minute");
    comboBox1.DataSource = new BindingSource(comboboxValues, null);
    comboBox1.DisplayMember = "Value";
    comboBox1.ValueMember = "Key";
    comboBox1.SelectedItem = comboboxValues[45000];
}



回答2:


Simply use

comboBox1.SelectedValue=45000

and your combo box will be pre selected by using Key



来源:https://stackoverflow.com/questions/12608189/setting-selected-item-in-combobox-bound-to-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!