簡體   English   中英

如何顯示組合框值而不是顯示對象名稱

[英]How to display comboBox value instead displaying name of objects

大約 3 個小時我試圖解決這個問題。 我的組合框向我顯示對象名稱而不是一個值,例如:A

在此處輸入圖片說明

這是我的課:

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 中,我試圖獲取所有產品並在組合框和標簽中表示它們。

在這種情況下我能做什么?

您需要將綁定源中的一個屬性指定為其將要顯示的DisplayMember ,並指定與其ValueMember相同或另一個屬性,您可以通過selectedItem.Value訪問

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

您應該像這樣覆蓋類的 toString() 方法:

public override String toString(){
    return name;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM