' data structure to hold details of a product Public Class Product Public name As String ' name of product Public cost As Double ' cost of product Public nbuy As Integer ' number purchased ' create a new Product Public Sub New(ByVal name As String, ByVal cost As Double) Me.name = name Me.cost = cost Me.nbuy = 0 End Sub End Class ' grocery store program Public Class Grocery ' list of goods Dim Goods As New List(Of Product) ' display list of goods Public Sub ListShop() ShopList.Items.Clear() For Each prod As Product In Goods ShopList.Items.Add(prod.cost.ToString("F02") & " " & prod.name) Next End Sub ' display contents of basket Public Sub ListBasket() BasketList.Items.Clear() For Each prod As Product In Goods If prod.nbuy > 0 Then BasketList.Items.Add(prod.nbuy.ToString("##") & " @ " & prod.cost.ToString("F02") & " " & prod.name) End If Next CalcTotal() End Sub ' find index of goods given name Public Function FindGoods(ByVal str As String) As Integer For i As Integer = 0 To Goods.Count - 1 If str.Contains(Goods(i).name) Then Return i Next Return -1 End Function ' calculate basket total Public Sub CalcTotal() Dim ngoods As Integer = 0 Dim total As Double = 0 For Each prod As Product In Goods ngoods += prod.nbuy total += prod.nbuy * prod.cost Next TotalText.Text = ngoods & " items = " & total.ToString("F02") End Sub ' initialise Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Goods.Add(New Product("Apple", 0.25)) Goods.Add(New Product("Bacon", 2.99)) Goods.Add(New Product("Cheese", 1.65)) Goods.Add(New Product("Dental Floss", 0.99)) Goods.Add(New Product("Eggs", 1.2)) ListShop() ListBasket() End Sub ' add product to basket Private Sub AddButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddButton.Click Dim idx As Integer = ShopList.SelectedIndex If (idx < 0) Then MsgBox("Please select an item from the store to add") Else Dim gidx As Integer = FindGoods(ShopList.Items(idx)) If gidx >= 0 Then Goods(gidx).nbuy += 1 End If ListBasket() End If End Sub ' remove product from basket Private Sub RemoveButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RemoveButton.Click Dim idx As Integer = BasketList.SelectedIndex If (idx < 0) Then MsgBox("Please select an item from the basket to remove") Else Dim gidx As Integer = FindGoods(BasketList.Items(idx)) If gidx >= 0 Then Goods(gidx).nbuy -= 1 End If ListBasket() If idx < BasketList.Items.Count Then BasketList.SelectedIndex = idx End If End If End Sub End Class