gpt4 book ai didi

c# - 如何显示组合框值而不是显示对象名称

转载 作者:行者123 更新时间:2023-11-30 14:50:31 25 4
gpt4 key购买 nike

我尝试解决这个问题大约需要 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 中,我试图获取所有产品并在组合框和标签中表示它们。

遇到这种情况我该怎么办?

最佳答案

您需要将绑定(bind)源中的一个属性指定为将要显示的 DisplayMember 以及与其 ValueMember 相同或另一个属性,您可以通过selectedItem.Value

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

关于c# - 如何显示组合框值而不是显示对象名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36357312/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com