【问题标题】:How to set Selectedvalue in Combobox c#如何在 Combobox c# 中设置 Selectedvalue
【发布时间】:2017-11-02 15:48:37
【问题描述】:

我有一个组合框,我在其中设置了数据源值,但是当我尝试设置 SelectedValue 时,组合框返回 null。所以请帮忙。

BindingList<KeyValuePair<string, int>> m_items =
                     new BindingList<KeyValuePair<string, int>>();

for (int i = 2; i <= 12; i++)
    m_items.Add(new KeyValuePair<string, int>(i.ToString(), i));
ComboBox cboGridSize = new ComboBox();
cboGridSize.DisplayMember = "Key";
cboGridSize.ValueMember = "Value";
cboGridSize.DataSource = m_items;

cboGridSize.SelectedValue = 4;

当我将 SelectedValue 设置为 4 时,它返回 NULL。

【问题讨论】:

  • 无法复制。此代码适用于默认的 winforms 组合框。你在写什么样的应用程序? WinForms、WPF、ASP.NET?
  • 把4改成“4”
  • 我正在使用 Winforms
  • 你好@Steve 现在试试.. 我已经编辑了我的代码
  • 你好@Laazo 我已经尝试过你的解决方案但不起作用..

标签: c#


【解决方案1】:

同意@Laazo 改为字符串。

cboGridSize.SelectedValue = "4";

或类似的东西

int selectedIndex = comboBox1.SelectedIndex;
Object selectedItem = comboBox1.SelectedItem;

MessageBox.Show("Selected Item Text: " + selectedItem.ToString() + "\n" +
"Index: " + selectedIndex.ToString());

并参考这看起来好像对您的问题有好处:

【讨论】:

    【解决方案2】:

    我在尝试解决这个问题的同时也遇到了这个问题。我通过创建以下扩展方法解决了这个问题。

            public static void ChooseItem<T>(this ComboBox cb, int id) where T : IDatabaseTableClass
        {
            // In order for this to work, the item you are searching for must implement IDatabaseTableClass so that this method knows for sure
            // that there will be an ID for the comparison.
    
            /* Enumerating over the combo box items is the only way to set the selected item.
             * We loop over the items until we find the item that matches. If we find a match,
             * we use the matched item's index to select the same item from the combo box.*/
            foreach (T item in cb.Items)
            {
                if (item.ID == id)
                {
                    cb.SelectedIndex = cb.Items.IndexOf(item);
                }
            }
        }
    

    我还创建了一个名为 IDatabaseTableClass 的接口(可能不是最好的名称)。这个接口有一个属性,int ID { get;放; } 确保我们确实有一个 ID 可以与参数中的 int id 进行比较。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-09
      • 1970-01-01
      • 2023-04-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-24
      • 2011-09-10
      • 2021-03-26
      相关资源
      最近更新 更多