将组合框中的选定项设置为绑定到字典

bmt*_*033 3 .net combobox dictionary selecteditem winforms

我有一个组合框,绑定到这样的字典:

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";
Run Code Online (Sandbox Code Playgroud)

我从SelectedItem获取密钥如下:

int selection = ((KeyValuePair<int, string>)comboBox1.SelectedItem).Key;
Run Code Online (Sandbox Code Playgroud)

因此,如果我的用户选择"45秒"选项,我将返回45000并将该值保存到XML文件中.当我的应用程序加载时,我需要读取该值,然后自动设置组合框以匹配.当我只有45000的键时,是否可以这样做?或者我需要将值("45秒")保存到文件而不是密钥?

pap*_*zzo 6

是的你可以只使用45000

comboBox1.SelectedItem = comboboxValues[45000];
Run Code Online (Sandbox Code Playgroud)

如果您知道索引,那么您可以使用

comboBox1.SelectedIndex = i;
Run Code Online (Sandbox Code Playgroud)

我基于零,-1表示没有选择.

或者设置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];
}
Run Code Online (Sandbox Code Playgroud)