通过键而不是值c#设置ComboBox选择的项目

set ComboBox selected item by Key not by value c#

在post这个问题之前,我认为这是一个简单的问题,我搜索了答案但没有找到合适的解决方案。

在我的日常工作中,我使用 Web 应用程序并且可以轻松地获取或设置下拉列表的值

我不能在 windows 应用程序 C# 中做同样的事情

我有组合框和 class comboItem

 public class ComboItem
    {
        public int Key { get; set; }
        public string Value { get; set; }
        public ComboItem(int key, string value)
        {
            Key = key; Value = value;
        }
        public override string ToString()
        {
            return Value;
        }
    }

假设组合框是通过硬代码绑定的,并且值为

假设我有 Key =3 并且我想通过代码设置这个项目(它的 key 是 3 ) 所以当加载表单时,默认选择的值将是未知的。

combobox1.selectedValue =3 //Not Working , selectedValue used to return an object
combobox1.selectedIndex = 2 //Working as 2 is the index of key 3/Unknown

但是假设我不知道索引,我怎样才能得到键 = 3 的项目的索引?

index可以这样通过value得到

int index = combobox1.FindString("Unknown") //will return 2

FindString 采用值而不是键,我需要像 FindString 这样的东西,它采用键和 return 索引

注意: 这是我绑定下拉菜单的方法

 JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings();
                        jsonSerializerSettings.MissingMemberHandling = MissingMemberHandling.Ignore;

                        var empResult= await response.Content.ReadAsStringAsync();
                        List<Emp> Emps= JsonConvert.DeserializeObject<Emp[]>(empResult, jsonSerializerSettings).ToList();
                        foreach (var item in Emps)
                        {
                            ComboItem CI = new ComboItem(int.Parse(item.ID), item.Name);
                            combobox1.Items.Add(CI);
                        }
                        this.combobox1.DisplayMember = "Value";
                        this.combobox1.ValueMember = "Key";

您需要设置 ValueMember 属性 以便 ComboBox 知道 属性 在使用 SelectedValue 时要处理什么。默认情况下 ValueMember 将为空。所以当你设置SelectedValue时,ComboBox不知道你要设置什么

this.comboBox1.ValueMember = "Key";

通常情况下,您还会设置 DisplayMember 属性:

this.comboBox1.DisplayMember = "Value";

如果您不设置它,它只会在对象上调用 ToString() 并显示它。在你的情况下 ToString() returns Value.

how can i get the index of item whose key = 3 ?

如果你想要key为3的item,为什么要从combobox中获取呢?您可以从组合框绑定到的集合中获取它:

例如,想象一下:

var items = new List<ComboItem> { new ComboItem(1, "One"),
    new ComboItem( 2, "Two") };

this.comboBox1.DataSource = items;
this.comboBox1.DisplayMember = "Value";
this.comboBox1.ValueMember = "Key";

this.comboBox1.SelectedValue = 2;

如果我需要key为2的项目,那么这将实现:

// Use Single if you are not expecting a null
// Use Where if you are expecting many items
var itemWithKey2 = items.SingleOrDefault(x => x.Key == 2);