How do I add menu items from a class list to another list of items in VB form?

Viewed 76

So I have created a menu form in VB, which asks user to select items from the menu and then uses the prices to calculate the total. For this I have created 2 lists, one of which is in the main form:

Dim menu As New List(Of MenuItem) From
 {
     New MenuItem With {.Name = "Burger", .Cost = 2.0 * txtburger.Text},
     New MenuItem With {.Name = "wrap", .Cost = 2.0 * txtwrap.Text},
     New MenuItem With {.Name = "Parmesan", .Cost = 2.5 * txtparmesan.Text},
     New MenuItem With {.Name = "Stirfry", .Cost = 3.0 * txtstirfry.Text},
     New MenuItem With {.Name = "pitta", .Cost = 2.5 * txtpitta.Text},
     New MenuItem With {.Name = "bundle", .Cost = 6.0 * txtbundle.Text},

This list uses a 'MenuItem' class to create items in the menu and set their prices.

The second list is in the 'order' class:

Public Property Items As List(Of MenuItem) = New List(Of MenuItem) 

Public Sub AddItem(ByVal item As MenuItem)

        Items.Add(item)

    End Sub

This class uses an 'AddItem' method to add items from the full menu previously defined, into this list. The items added to this list here are the items which the user will select when the form is loaded.

But How do I instantiate an object in 'order' class, so the items that the user chooses get added to this list from the main form? Each item has a text box next to it in the form which determines the quantity of the item. So I will have to pass in a parameter for each item that gets selected. I'm not really sure how to do this.

Hope all this makes sense and I'm doing it right.

1 Answers

Plaese be carefull about adding your items from your main list to your order. That means that the same object is referenced several times and I think it's not what you want. You want distinct objects (and maybe several instances in the same order).

Knowing this, how to add new instances of your MenuItem to your Order ?

First, add a Clone function to MenuItem, that return a NEW MenuItem similar to current instance.

Function Clone() As MenuItem

    Return New MenuItem With {.Name = Me.Name, .Cost = Me.Cost}

End Function

Then you just have to use a loop to add as many items as you want :

Public Sub AddItem(ByVal item As MenuItem, ByVal count As Integer)

    For i As Integer = 0 To count - 1
        Items.Add(item.Clone())
    Next

End Sub

More tips :

  • Don't multiply the price of your MenuItem, each item should have the price of 1 item
  • The total price will be Items.Sum(Function(o) o.Cost) (which is the sum of all the cost of your items)
  • Don't keep your Items list public, it means that everybody can add items directly to it without calling a specific function
Related