【问题标题】:Setting selected item in combobox bound to dictionary在绑定到字典的组合框中设置所选项目
【发布时间】:2012-09-18 11:02:52
【问题描述】:

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

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 中获取密钥,如下所示:

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

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

【问题讨论】:

    标签: .net winforms dictionary combobox selecteditem


    【解决方案1】:

    简单地使用

    comboBox1.SelectedValue=45000
    

    您的组合框将通过使用键预先选择

    【讨论】:

      【解决方案2】:

      是的,你可以只使用 45000

      comboBox1.SelectedItem = comboboxValues[45000];
      

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

      comboBox1.SelectedIndex = i;
      

      i 从零开始,-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];
      }
      

      【讨论】:

      • 我一直在尝试您的第一个建议 (comboBox1.SelectedItem = comboboxValues[45000];),但它对我不起作用。没有发生错误,只是没有产生预期的效果。我目前正在为键使用 switch 语句,然后根据您的第三个建议设置 SelectedItem。这对我有用,但我觉得硬编码开关值不是一个非常灵活的解决方案。关于为什么您的第一个建议似乎不起作用的任何想法?
      • 那是我实际测试过的代码。我希望你先把那个kvp放在字典里?并绑定它。
      • 很奇怪。我刚刚创建了一个新的 WinForms 应用程序,将上面的确切代码粘贴到 Form1_Load 事件处理程序中,并在调试器中单步执行。当我的表单出现时,组合框显示“30 秒”(正如我对 comboBox1.SelectedItem = comboboxValues[30000]; 语句所期望的那样)。但是,然后我返回并将该行编辑为 comboBox1.SelectedItem = comboboxValues[45000] ,当表单出现时,组合框仍显示“30 秒”而不是“45 秒”。如果它对你有用,我一定会在这里遗漏一些明显的东西,但我肯定不知道它是什么。 :-(
      • 你修改值后编译了吗?
      • 当然可以。非常非常奇怪。我将不得不花一些时间试图弄清楚发生了什么。这应该非常简单,对你有用,但对我没有用。啊!尽管如此,还是感谢您的所有建议。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多