RayB151
RayB151

Reputation: 139

Displaying separate items in a listbox from a collection

I'm making a shopping basket winforms app that will take input from the user, who will specify a product name, a price and a quantity.

I have a dll with some methods relating to the app and a constructor that creates a list - I have instantiated this in my winforms code.

The issue I am having is that I am unable to separate different products in the listbox, it would replace the previous item the user entered e.g. it currently would read:

Product     Price      Quantity
Bread       3.60       3
Milk        6.57       5
Eggs        8.97       7
Bread       11.37      9

Where I would like it to read:

Product     Price      Quantity
Bread       6.00       5
Milk        1.19       2
Eggs        1.50       2

I would like it to show each item separately, with it's corresponding price and current quantity.

I have tried using a foreach loop to iterate through the basket but I get an error:

foreach statement cannot operate on variables of type 'namespace.ShoppingBasket' because 'namespace.ShoppingBasket' does not contain a public definition for 'GetEnumerator'

Should I be using an interface to achieve this?

Upvotes: 1

Views: 207

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236218

Your ShoppingBasket class does not implement interface IEnumerable which is required if you want to enumerate basket in foreach. If you don't want to implement that interface from scratch you can inherit from some class which already implements it (e.g. List<T>).

E.g. if you store order items in a list, you can return it's enumerator:

public class ShoppingBasket : IEnumerable<OrderItem>
{
    private List<OrderItem> items = new List<OrderItem>();

    // ...

    public IEnumerator<OrderItem> GetEnumerator()
    {
        return items.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

NOTE: You also can just add IEnumerator GetEnumerator() method instead of implementing IEnumerable interface. That also will make foreach work.

Upvotes: 2

Related Questions