簡體   English   中英

通過鍵而不是按值設置ComboBox選定項c#

[英]set ComboBox selected item by Key not by value c#

在發布此問題之前,我認為這是一個簡單的問題,我正在尋找答案,卻找不到合適的解決方案。

在日常工作中,我正在使用Web應用程序,並且可以輕松獲取或設置下拉列表的值

我不能在Windows應用程序C#中執行相同的操作

我有combobox和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;
        }
    }

假設組合框通過硬代碼綁定,並且值是

  • 鑰匙:1 /價值:男性
  • 鑰匙:2 /價值:女性

  • 鍵:3 /值:未知

可以說我有Key = 3,並且我想通過代碼設置此項(其key為3),因此在加載form時,默認情況下選定的值為Unknown。

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的項的索引?

索引可以通過這種方式獲得價值

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

FindString取值而不是鍵,我需要像FindString這樣的東西,它取一個鍵並返回索引

注意:這是我綁定下拉菜單的方式

 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將為空。 因此,當您設置SelectedValueComboBox不知道您要設置什么。

this.comboBox1.ValueMember = "Key";

通常,您還可以設置DisplayMember屬性:

this.comboBox1.DisplayMember = "Value";

如果不設置它,它將僅在對象上調用ToString()並顯示它。 在您的情況下, ToString()返回Value

如何獲得鍵= 3的項的索引?

如果您想要鍵為3的項目,為什么需要從組合框中獲取它? 您可以從組合框綁定到的集合中獲取它:

例如,想象一下:

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;

如果我需要密鑰為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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM