如何显示comboBox的值而不是对象名称

5

我已经尝试了3个小时来解决这个问题。我的组合框显示对象名称而不是值,例如:A

enter image description here

这是我的类:

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循环中,我试图获取所有的产品,并将它们呈现在组合框和标签中。

在这种情况下我该怎么办?


请检查此链接:https://dev59.com/2HRB5IYBdhLWcg3wgXdV - rashfmnb
2个回答

9

您需要指定绑定源中的一个属性作为其DisplayMember,该属性将被显示,并且同一或另一个属性作为其ValueMember,您可以通过selectedItem.Value访问它。

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

1

您需要重写类的toString()方法,就像这样:

public override String toString(){
    return name;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接