問題描述
在綁定到字典的組合框中設置所選項目 (Setting selected item in combobox bound to dictionary)
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
(by bmt22033、paparazzo、Naveed Yousaf)