在组合框中设置所选项目绑定到字典 [英] Setting selected item in combobox bound to dictionary

查看:172
本文介绍了在组合框中设置所选项目绑定到字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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";

我从SelectedItem中获取键如下:

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

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

所以如果我的用户选择45秒选项,我回到45000并保存该值一个XML文件。当我的应用程序加载时,我需要读取该值,然后自动设置组合框匹配。是可能做到这一点,当我只有45000的关键吗?或者我需要将值(45秒)保存到文件而不是密钥?

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?

推荐答案

只使用45000

comboBox1.SelectedItem = comboboxValues[45000];

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

If you know the index then you can use

comboBox1.SelectedIndex = i;

i基于零,-1表示无选择。

i is zero based and -1 means no selection.

或设定SelectedItem

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];
}

这篇关于在组合框中设置所选项目绑定到字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆