2015-10-20 19 views
1

我想每個項目存儲兩個項目,例如名稱和說明。 所選項目將顯示名稱,標籤將顯示該項目的說明,只要所選項目被更改,標籤需要更新。組合框每個項目有兩個單獨的文本字段

我下面有什麼似乎存儲的項目,但不顯示基於選定的索引或每當項目選擇更改!

ComboboxItem item = new ComboboxItem(); 
      item.Text = "A1"; 
      item.Value = "A2"; 
      comboBox1.Items.Add(item); 

      item.Text = "B1"; 
      item.Value = "B2"; 
      comboBox1.Items.Add(item); 


      comboBox1.SelectedIndex = 0; 

      label1.Text = (comboBox1.SelectedItem as ComboboxItem).Value.ToString(); 



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

並與一類:

public class ComboboxItem 
    { 
     public string Text { get; set; } 
     public object Value { get; set; } 

     public override string ToString() 
     { 
      return Text; 
     } 
    } 
+0

你希望輸出是'B1'或'A1'要麼? –

+0

除非「描述」是識別「價值」,那麼它聽起來像你想要存儲*三個*數據元素,而不是兩個。 – David

+0

組合框將顯示A1和負載的標籤A2,如果他們選擇B1,則標籤應該用B2更新 – RTFS

回答

2

ComboBoxItem是引用類型。在將其添加到comboBox1項目之前,您必須創建新項目,否則它也會更改以前添加的項目。

更改這一部分

ComboboxItem item = new ComboboxItem(); 
item.Text = "A1"; 
item.Value = "A2"; 
comboBox1.Items.Add(item); 

// Will change value of item thus item added to combo box will change too because the references are same 
item.Text = "B1"; 
item.Value = "B2"; 
comboBox1.Items.Add(item); 

對此

ComboboxItem item = new ComboboxItem(); 
item.Text = "A1"; 
item.Value = "A2"; 
comboBox1.Items.Add(item); 

ComboboxItem item2 = new ComboboxItem(); 
item2.Text = "B1"; 
item2.Value = "B2"; 
comboBox1.Items.Add(item2); 
+0

謝謝,我完全錯過了!現在一切正常。 – RTFS

相關問題