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

时间:2015-03-28 12:20:11

标签: c# class listbox

我创建了一个名为product的类,我在我的主程序中添加了不同的产品,如下所示:

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语句,因为会有超过200个if语句。如果在这个问题上有任何不清楚的地方,请告诉我。

1 个答案:

答案 0 :(得分:2)

只需使用Product填充ListBox,而不是字符串:

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;
相关问题