2016-04-01 75 views
1

大約3小時我正試圖解決這個問題。例如對象,而不是一個值的我的組合框中顯示我的名字:一個 enter image description hereC#如何顯示組合框的值,而不是顯示對象的名稱

這是我的課:

namespace Supermarket 
{ 
    public class WhareHouseTable 
    { 
     public string name { get; set; } 
     public double cost { get; set; } 
     public string offer { get; set; } 
    } 
} 

這裏是我的代碼:

private void Form1_Load(object sender, EventArgs e) 
     { 
      List<WhareHouseTable> product = new List<WhareHouseTable>(); 
      product.Add(new WhareHouseTable { name = "A", cost = 0.63, offer = "Buy 2 for the price of 1" }); 
      product.Add(new WhareHouseTable { name = "B", cost = 0.20 }); 
      product.Add(new WhareHouseTable { name = "C", cost = 0.74, offer = "Buy 2; get B half price" }); 
      product.Add(new WhareHouseTable { name = "D", cost = 0.11 }); 
      product.Add(new WhareHouseTable { name = "E", cost = 0.50, offer = "Buy 3 for the price of 2" }); 
      product.Add(new WhareHouseTable { name = "F", cost = 0.40 }); 

      comboBox2.DataSource = product; 
      comboBox2.DropDownStyle = ComboBoxStyle.DropDownList; 

      source.DataSource = product; 

      foreach (var selected in product) 
      { 
       comboBox2.Text = selected.name; 
       itemCostLabel.Text = selected.cost.ToString(); 
       offerLabel.Text = selected.offer; 
      } 

     } 

在的foreach我我試圖獲得所有產品,並在comboBox和標籤中表示它們。 在這種情況下我能做些什麼?

+0

檢查此ilnk http://stackoverflow.com/questions/600869/how-to-bind-a-list-to-a-combobox-winforms – rashfmnb

回答

3

你需要指定綁定源爲DisplayMember這是會被顯示,相同或另一個屬性爲ValueMember您可以通過selectedItem.Value

comboBox2.DisplayMember = "Name"; 
    comboBox2.ValueMember = "Name"; 
-1

您應該重寫的toString訪問屬性之一()這樣的類的方法:

public override string ToString() 
    { 
     return name; 
    } 
相關問題