根据列表框中的选定项显示 class 中的 属性 的值

Displaying the value of a property from a class according to selected item in listbox

我制作了一个名为 class 的产品,并在我的主程序中向我的 class 添加了不同的产品,如下所示:

product1 = new Product();
product1.Name = "product1";
product1.Price = 3.50;

Product product2 = new Product();
product2.Name = "product2";
product2.Price = 4;

我有一个列表框,我用这个方法填充:

private void fillProducts(string item)
        {
            lstProducts.Items.Add(item);
        }

所以当我使用该方法时,它看起来像这样:fillProducts(product1.Name);

现在我想要实现的是,当我按下按钮 (btnConfirm) 时,它会看到在列表框中选择了哪个产品并获取产品的价格并将其显示在标签中

lblConfirm.Text = "The price of product1 is: " + *the price of product1*;

所以我需要在我的标签中显示 product1 的价格,我不想对每个产品都使用 if 语句,因为 if 语句会超过 200 个。如果这个问题有什么不清楚的地方请告诉我。

只需使用 Product 而非字符串填充列表框:

private void fillProducts(Product item)
{
    lstProducts.Items.Add(item);
}

使用 ListBox 的内置属性告诉它要显示什么值:

lstProducts.DisplayMember = "Name";

然后访问SelectedItem 属性以在需要时获取所选项目:

var price = ((Product)lstProducts.SelectedItem).Price

lblConfirm.Text = "The price of product1 is: " + price;