Reputation: 104
I made a class named product and I added different products to my class in my main program like this:
product1 = new Product();
product1.Name = "product1";
product1.Price = 3.50;
Product product2 = new Product();
product2.Name = "product2";
product2.Price = 4;
And I've got a listbox which I fill with this method:
private void fillProducts(string item)
{
lstProducts.Items.Add(item);
}
So when I use the method it would look like this: fillProducts(product1.Name);
Now what I want to achieve is that when I press a button (btnConfirm) it would see which product has been selected in the listbox and get the price of the product and display it in a label
lblConfirm.Text = "The price of product1 is: " + *the price of product1*;
So I need to display the price of product1 in my label and I don't want to use if-statements for every single product because there would be over 200 if-statements. If anything is unclear in this question please tell me.
Upvotes: 3
Views: 73
Reputation: 66449
Just populate the ListBox with a Product
, not a string:
private void fillProducts(Product item)
{
lstProducts.Items.Add(item);
}
Use properties built-in to the ListBox to tell it what value to display:
lstProducts.DisplayMember = "Name";
Then access the SelectedItem
property to get the selected item when you need it:
var price = ((Product)lstProducts.SelectedItem).Price
lblConfirm.Text = "The price of product1 is: " + price;
Upvotes: 2