Visual Basic | Creating classes exercise | Create classes to facilitate writing your shopping list

This exercise is provided to allow potential course delegates to choose the correct Wise Owl Microsoft training course, and may not be reproduced in whole or in part in any format without the prior written consent of Wise Owl.

Software ==> Visual Basic  (46 exercises)
Version ==> Any version of VB
Topic ==> Creating classes  (4 exercises)
Level ==> Relatively easy
Subject ==> Visual Basic training
Before you can do this exercise, you'll need to download and unzip this file (if you have any problems doing this, click here for help).

You need a minimum screen resolution of about 700 pixels width to see our exercises. This is because they contain diagrams and tables which would not be viewable easily on a mobile phone or small laptop. Please use a larger tablet, notebook or desktop computer, or change your screen resolution settings.

Right-click on your project in Solution Explorer and choose to add the form from the above folder (you can alternatively press SHIFT + ALT + A ).

Blank form

The initial form. The idea is that when you type in an item and click on the Add Item button, it will be added to the list on the right.

First add code to the Cancel button so that clicking on it closes the form.

Remember that you can use me to refer to the current form.

Create a class called ShoppingList.  Within this, create 3 simple properties, to hold the item name, unit and amount.  Here's an example for the item name:

'item name property

Private _ItemName As String = ""

Public Property ItemName As String


Return _ItemName

End Get

Set(value As String)

_ItemName = value

End Set

End Property

You should now be able to attach code to the Add Item button which:

  • Creates a new instance of your ShoppingList class;
  • Sets the item name, unit and amount properties.

The only thing you need to add now is the code to add the item to the textbox on the right of the form.  To do this you could add a public method to your class, which passes in the textbox to which you want to add text:

Public Sub Add(ListTextBox As TextBox)

'add a blank line if appropriate

If ListTextBox.Text.Length > 0 Then _

ListTextBox.Text &= vbCrLf

'add item to the list of items

ListTextBox.Text &= Amount.ToString("0.00") & _

" " & Unit & " of " & ItemName

End Sub

Make sure that you call this method at the end of your Add Item button code, and test your system to check that it accumulates items to buy:

Shopping list

You'll gradually accumulate items in your list.


Test that your system works, then close the form down (don't worry for now that this will then lose your shopping list!). 

You can unzip this file to see the answers to this exercise, although please remember this is for your personal use only.
This page has 0 threads Add post