C# 如何在组合框c中设置Selectedvalue

C# 如何在组合框c中设置Selectedvalue,c#,C#,我有一个组合框,其中设置了数据源值,但当我尝试设置SelectedValue时,组合框返回null。所以请帮忙 BindingList<KeyValuePair<string, int>> m_items = new BindingList<KeyValuePair<string, int>>(); for (int i = 2; i <= 12; i++) m_items.Add(new

我有一个组合框,其中设置了数据源值,但当我尝试设置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。

同意@Laazo更改为字符串

cboGridSize.SelectedValue = "4";
或者类似的事情

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

MessageBox.Show("Selected Item Text: " + selectedItem.ToString() + "\n" +
"Index: " + selectedIndex.ToString());
并参考以下内容,似乎这对您的问题有好处:


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

        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;set;},以确保我们实际上有一个ID与参数中的int-ID进行比较。

无法复制。此代码使用默认的winforms组合框。你在写什么样的申请书?WinForms,WPF,ASP.NET?将4更改为4我正在使用WinformsHello@Steve现在试试。。我已经编辑了我的代码Hello@Laazo我已经尝试了你的解决方案,但没有效果。。