2017-09-13 59 views
0

所以我有Combo Box,我有一個使用KeyValuePair<int, decimal>製作的列表。我希望我選擇的文本框在我從下拉式文本框中選擇時根據鍵顯示值。從ComboBox Dropdown中選擇後文本框不顯示值

相關代碼:

// Make a list of truck weight and MPG. 
List<KeyValuePair<int, decimal>> weightMPG = new List<KeyValuePair<int, decimal>>(); 

private void mainForm_Load(object sender, EventArgs e) 
{ 
    decimal k = 7; 
    for (int i = 20000; i < 40000; i+=1000){ 
     weightMPG.Add(new KeyValuePair<int, decimal>(i, k)); 
     k -= 0.1m; 
    } 
    for (int i = 40000; i < 45000; i+=1000){ 
     weightMPG.Add(new KeyValuePair<int, decimal>(i, 5)); 
    } 
    weightMPG.Add(new KeyValuePair<int, decimal>(46000, 4.9m)); 
    weightMPG.Add(new KeyValuePair<int, decimal>(47000, 4.8m)); 
    weightMPG.Add(new KeyValuePair<int, decimal>(48000, 4.7m)); 
    truckWeight2.DataSource = weightMPG; 
    truckWeight2.ValueMember = "Value"; 
    truckWeight2.DisplayMember = "Key"; 
} 

private void truckWeight2_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    truckMPG2.Text = truckWeight2.ValueMember; 
} 

對於這段代碼,它顯示了從20,000到48,000下拉當我點擊控制。但是,當我選擇一個時,文本框(truckMPG2)不會更新以反映該值,而是始終顯示單詞「值」。

我在查看其他堆棧溢出的答案時,使這個代碼,所以我不知道我錯了。

回答

4

您正在閱讀的.ValueMember屬性:

truckMPG2.Text = truckWeight2.ValueMember; 

您專門設置爲一個字符串:

truckWeight2.ValueMember = "Value"; 

這聽起來像你想的.SelectedValue屬性來代替:

truckMPG2.Text = truckWeight2.SelectedValue; 

或者,如果類型不匹配,但值可以直接表示爲一個字符串,則可能需要追加.ToString()的值:

truckMPG2.Text = truckWeight2.SelectedValue.ToString(); 
+0

也許它會清除掉,但我基本上要在文本框中顯示相應的十進制數。例如20,000 - > 7; 21,000-> 6.9等。我不知道爲什麼我將ValueMember設置爲Value,我只是嘗試從SO答案中獲得東西。 – Annabelle

+0

@Annabelle:等等,當您將'.ValueMember'設置爲'「Value」時,列表是否不顯示正確的值?更改選擇時,「.SelectedValue」是什麼?不要從Stack Overflow的答案中複製/粘貼代碼。特別是寫執行你想要執行的操作的語句。如果您不確定給定語句的作用,請查看文檔並在調試器中對其進行試驗,以瞭解其功能。 – David

+0

列表本身顯示正確的成員(鍵)。然而,我想要的值的文本框(例如7,6.9..etc)僅顯示單詞「值」。也使用'.SelectedValue;'時,我只是得到一個鑄造錯誤。 – Annabelle

相關問題