2017-06-04 144 views
0

在發佈此問題之前,我認爲這是一個簡單的問題,我搜索答案並沒有找到合適的解決方案。設置ComboBox按鍵不是按值選擇項c#

在我的日常工作

,我與Web應用程序的工作,並可以很容易地獲取或設置

我不能做相同的Windows應用程序C#dropdownlists值

我有組合框和階級的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 /值:未知

可以說,我有鑰匙= 3,我想通過代碼 設置這個項目(其關鍵是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?

指數可在這樣

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

查找字符串取一個值不是關鍵,通過價值的東西,我需要像查找字符串內搭鍵和返回指數

注: 這裏是如何我結合我的下拉菜單

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"; 
+0

Windows Forms? WPF?要麼 ? –

+0

Windows窗體C# – Bassem

回答

2

您需要設置ValueMember屬性,以便在ComboBox知道什麼財產處理當SelectedValue正在使用。默認情況下,ValueMember將爲空。所以當你設置SelectedValue時,ComboBox不知道你想要設置什麼。

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); 
+0

非常感謝@CodingYoshi和非常好的信息,爲什麼我需要從組合框中獲取它的原因是我試圖在不同的位置/功能獲取它,而不是它綁定的位置,你有什麼想法嗎? – Bassem

+0

我試過這個comboSubscriptionType.SelectedValue = 12,並且在調試這一行之後,SelectedValue仍然爲null,我添加了comboBox1.DisplayMember =「Value」; comboBox1.ValueMember =「Key」; 在我綁定的地方 – Bassem

+0

你有一個項目與關鍵12?要回答您之前的評論,您始終可以將對數據源的引用存儲爲類級別字段。或者你可以像這樣從組合框中投射它:'(列表)this.comboBox1.DataSource' – CodingYoshi