【问题标题】:Displaying the value of a property from a class according to selected item in listbox根据列表框中的选定项目显示类中的属性值
【发布时间】:2015-03-28 12:20:11
【问题描述】:

我创建了一个名为 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 语句。如果这个问题有什么不清楚的地方,请告诉我。

【问题讨论】:

    标签: c# class listbox


    【解决方案1】:

    只需使用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;
    

    【讨论】:

    • 它可以工作,但在我的列表框中它会显示 projectname.Products 很多次(每个产品一次),当我按下确认按钮时,它会正确显示名称,您是否知道是什么原因造成的这个?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-20
    • 1970-01-01
    • 2011-08-03
    • 2018-10-29
    • 1970-01-01
    • 2017-02-14
    • 2020-10-01
    相关资源
    最近更新 更多