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

cygmwpex  于 2022-11-16  发布在  其他
关注(0)|答案(2)|浏览(190)

大约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中,我试图获取所有产品,并在comboBox和标签中表示它们。
在这种情况下我能做什么?

q9yhzks0

q9yhzks01#

您需要将绑定源中的一个属性指定为要显示的DisplayMember,并将相同或其他属性指定为可通过selectedItem.Value访问的ValueMember

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

z31licg02#

您应该覆写类别的toString()方法,如下所示:

public override String toString(){
    return name;
}

相关问题