2017-04-18 103 views
0

我想顯示一定的值到一個標籤,取決於在comboBox中選擇的項目,comboBox中的每個項目將顯示不同的值,問題是組合框有很多項目和每個人都需要顯示不同的值C#更改標籤取決於組合框選擇索引

private void comboBox_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    switch (comboBox.SelectedIndex) 
     { 
      case 0: 
       if (comboBox.SelectedIndex == 0) 
       { 
        Label.Text = "8"; 
       } 
       break; 
      case 1: 
       if (comboBox.SelectedIndex == 1) 
       { 
        Label.Text = "15"; 
       } 
       break; 
      case 2: 
       if (comboBox.SelectedIndex == 2) 
       { 
        Label.Text = "60"; 
       } 
       break; 
     } 
}      

我該如何改進並縮短它?我被告知要使用一個對象數組,但是如何驗證哪個項目被選中?

回答

0

這是使用列表讓你的代碼更短的例子:

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) 
    { 
     IList<string> lstString = new List<string>(); 
     lstString.Add("Hello"); 
     lstString.Add("World"); 
     lstString.Add("Foo"); 
     lstString.Add("C#"); 
     lstString.Add("StackOverflow"); 
     label1.Text = lstString[comboBox1.SelectedIndex]; 
    } 

由於名單開始於指數零和ComboBox索引零開始,你可以調用列表以匹配的索引你的組合框的索引。

+0

的事件代碼,謝謝!這種清單是我需要的,但我自己無法弄清楚 –

+0

不客氣!您現在可以接受它作爲參考其他程序員的答案。 @RobertoMTorres –

0

你可以做你的組合框的初始化。(把它放在load事件形式或其他地方取決於你的需要。)

var listCombo = new List<int>(); 
listCombo.Add(8); 
listCombo.Add(15); 
listCombo.Add(60); 
listCombo.ForEach(m => comboBox1.Items.Add(m.ToString())); 

然後,你可以指定在標籤所選項目組合框

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    label1.Text = comboBox1.SelectedItem.ToString(); 
} 

enter image description here