0% found this document useful (0 votes)
3 views

Pizza App

The document provides a guide on using Visual Studio Community to create a Windows Forms application in Python. It details the steps to set up a project, create a user interface with various controls, and write code to handle user input and perform calculations. Additionally, it explains the importance of naming conventions for objects and variables in programming.

Uploaded by

dil0001
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Pizza App

The document provides a guide on using Visual Studio Community to create a Windows Forms application in Python. It details the steps to set up a project, create a user interface with various controls, and write code to handle user input and perform calculations. Additionally, it explains the importance of naming conventions for objects and variables in programming.

Uploaded by

dil0001
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Programming Ill

We have learned some basic programming skills in Python in previous chapters. We are going to use
a fast development environment that allows you to use Windows objects to quickly and easily create
an interface. The development environment is called Visual Studio Community and it is free to
download from here: https://visualstudio.microsoft.com/downloads/
To use the free version of Visual Studio you will need to sign into a Microsoft Account. Once you have
logged in and opened Visual Studio you need to create a New Project. Ensure your project setting is
"Windows Forms App" (.NET Framework). You can search for it using the language: Visual Basic and
the platform: Windows and Desktop.
You can see in Fig 3.26 below that we need to give our first project and solution a name. We also need
to identify the location where the project will be stored. Be warned: Once you name your project and
identify the location, you can not change it! Ensure you remember the name of the project, and
where it is located before selecting "Create"!
Once you create your project you will be presented with
a blank form. A form is a window that allows you to
create an interface between the user and the code you
will write.
There are four things that need to be visible on our
screen to start making an window 3. the Properties [ c..w ... 11.,,�,01111o�od.c1.,,,,;;VI\_
Soluh,,n...,..O

application: 1. a Form window --


:I
2. the Solutions Explorer Configure your new project Windows Forms App
(.NET Framework)

�.,, .. v.m
4. the Toolbox. r�r·-:��•u_ -J
See the screen shot below for access and set up
these resources.
... �
['."'.::. ... _ - _- ]
01'1o<,.Ju1.,.,,..,1,,.,
,..1.,11,. ... n•<lo<•<I<..-,

Fg_rmat T�t Analyze. Iools f!te.nsions �indow .!:::!elp


Debug .. Any CPU

Search Solution Explorer (


_Ctr! .... ;�
t;jj Solution 'MyFirst:App' (1 of 1 project)
.i1 � MyfirstApp
J, My Project
t,) •·■ References
f-j App.config
� � Forn,1.vb
0

Set up Toolbox Properties


and Solution Explorer in
this panel for easy access.

Page 122
r m,;b } -11 •
'4 lI• t eN f<0Je<t l! ld Q,bug T.,t ,ly,•
uo
n
l• E,t,n oo , '/J_mdow
oo

1:!•IP


tbug • A CPU • ► St rt • p ;

� . _. y JI
��! ust\liew
k
(). Mas dT extB ox
ffl
0 MonthC1l r
i
b Not con
[i Num
t U D on
liJ Picturt
011:
IE Progru
0R
di Butto n
:l
ich x
eckB T
Ch ox 13 Box
Ust t'3 ToolTi
ox p
; Chtck�

ffl C ':':: t el/i tw


-D
b oBo, •

� 01te 18 livt Share f;


eP ittr
A La
p My " l 0X
A Lin
l P·
� LinBcni:

In
' W
the diagram above you c n e e e f each f e r s a d e t to n. S l et s e are going to create a y p le . It ill read
h
in two values and add them tog he r, n
started.

s nt e l d W n e
display the answer on e c re . e st g e d to o s i gn e o l w the a to e d o es to d n t o , a n to e e
th
ro e ss of e ers
be read in a n d then di pl yed.
t gether, then a Label to display the ans er.
l
S t e x d t t p o t m on C
S a r ch T
o g x

e ll . se re e o ls e ll e ed r ll p o r . G t
ll W ndos

l A
m m Cont r
s

1 o o e x d t TextBox 2. Draw A
@
on
n s lit' Pn tr

a.
C
th Form (Clik and Dr 0 ckBox

the Tx n a g e h e x Ii!'\ C
g:: x �
e
Ti r

l
Le c n n e e x x s c td n he r m, n ab l

s e to e rm •X

T
o olb x

x

r oe r s ndo .
w .(
)
ext Bx !l:',l o nh
N c U
Cle r 6: oti l cn [j]
n

.:i x
i;;:J
r esB ar o n
0
•A h ext x
x
t;ei ol p
ew

z:i b Br
t> Containers
b ox

e 1 23

D<, file .Edit Yiew frojKt f!uild Qebug


Fgrmat Tli!,it
tfelp Debug • AriyCPU
An,lyu !ools E¥tensions t{iridow
.p
MyFlrstApp
• □

• • ► Start · P
fa• rt Iii � '? •
Forml.vb !Design)•
.g X
... Form!

Accepts Tab False


-·!I b,(Name) txtNumberl
"---9 Accepts Return False

AccessibleDescrip
AccessibleName
AccessibleRole Default
AllowDrop False
Anchor Top, Left
AutoCompleteCu, (Collection)
AutoCompleteMc None
AutoCompleteSrn None
II u1:-..1- ..
(Name)
Indicates the name used in code to
identify the object.
Properties

In the diagram above, you can see that the Properties Window is set up in alphabetical order so that each
property is easy to find. We use the (Name) property to change the name of the object selected. It is
important that you name your objects so that it is clear what type of object it is, and what it is used for.
In this case, the TextBox has been named txtNumberl. The 'txt' indicates that it is a TextBox and the
'Numberl' indicates that it will be used to input the first number.
Let's add another TextBox and name it "txtNumber2".
Using the same techniques, add a Label object to the Form below and change the name to ''lblAnswer".
This time we are going to change another property in the label. We are going to put a line of dots in the
"Text" property. This will display inside the Label. If you have the Properties Window set up
alphabetically, you will easily find the Text property. You can also change the Text property on the Form.
Click anyware in the Form and go to the Properties Window and change the Text property to
"Calculator".

Finally we will add a button. Again we use the same process:

1. Go to the Toolbox.

2. Select the Button.


3. Draw the Button between the two TextBoxes.
4. While the Button is selected go to the Properties Window.

5. Rename the Button "btnAdd".


6. Change the Text property to"+".
You should have something that looks like the screen diagram below.

oO fle [d� �fW f"'Jod ju,ld ll:tbug F11rmo1 Tqt A!!tlytt Jgol,; �Ull>Onl
�,ndaw ""' rJ ·,. Iii tf' ? • Dtbug • AiiyCPll • ► SUit •
fcrmLvb(Du,gn)' ,o Page 124
p - • - 0 lB LNeShHt fr

Form1 System.Windows.Forms.Form �!! �j, � ,


HI Padding 0, 0, 0, 0
RightToleft No
RightToleftlayou1 False
Showlcon True
ShowlnTaskbar True
EEi Size 822, 506
SizeGripStyle Auto
StartPosition WindowsDefaultloc. Tag
Text Calculator
TopMost False

TransparencyKey D
UseWaitCursor False
Text
T he text associated with the control. Proptrtits

The Role of Objects and


Variables

• Interface
.,j�c•ui.101
- +

Code

181
101•1

I ilM®i""ill\li/.l,li,i¥1◄1%h I
User
We have completed the interface. The diagram above illustrates the role that objects and variables have in
programming. An object is used on the interface. It allows the user to interact with the code. The objects
will assign the data to variables. The variables can be used to process the calculations. Once the data is
processed it must then passed on to objects on the screen so that the data can be displayed for the user to
see.
We can start coding our program.
A Visual Basic program requires FOUR sections:
1. Declare the variables.
2. Input the data.
3. Process the data.
4. Output the processed data.
We know we need three objects to handle the input and output of the data, so we will probably need three
variables to handle the data for processing.
In the diagram above there are three variables identified:
intNumberl
intNumber2
intAnswer

e
yv _are using the same approach to naming our variables as we did naming our objects. The "int" mdicates
an integer data type. The "Numberl" identifies which value and it's association with a corresponding
object. All of our variables will be handling integers so we need to declare them as integers in our code.

To ?egin coding we need to identify which object will execute the code. We have added a button which is
designed to execute code when clicked by the user.
Simply double click on your button and a new window will open so you can type your code in. Page 125

Forml 11b [Des19nj•


)'�:5t" :���!!,�!1..,!�:���
"t
1 �•,::(y �(¾..:\:: �� •-� � ";,
Forml.vb- .g X l!!!J MyFi"tApp _ ·(�btnAdd • • f Click

ecferer-:iiS • EPublic Class =crrr.1


E:. Private Sub BtnAdd_Click(sender As Object� e As EventA-gs) Handlu btnAdd.Click

4 L End Sub
5 fend Class

In Fig. 3.27 above, you can see tlie code window for our new program. It has
already written some lines of code for us. On Line 1 is Identifies the Public
Class as Form 1. This is the name of our Form that we are currently using.
Line 2 is a private sub-routine that will execute when BtnAdd is clicked. Line
4 ends the sub-routine and Line 5 ends the whole program. Programs can have
many sub-routines.
We are going to write our code between the Private Sub BtnAdd_Click and End Sub.
First we need to declare the variables. We use Dim which is short for
dimension. It will become clearer why, when you learn more about data
structures later in the Specialist subjects.

1 referc.rc:

1 Handles btnAdd.Click
E]Public Class =orml 0
re.fi:rer�e::: Object, e As EventA�gs)
2 3 4 5
As Integer 6 Integer7
El. Dim intNumber2 As
Private Sub Integer intNumberl = Declaring the
BtnAdd_Click(sender Dim intAnswer As txtNumberl. Text Variables
As Di� intNumberl

intNumber2 = txtNumber2,Text Reading the data into variables from objects


8
9
intAnswer = intNumberl + intNumber2
Calculating the Answer with variables 10 11
lblAnswer. Text = intAns1�er
12
End Sub
13

End Class Sending the calculated data to the display object.


14
15

In the code above, lines 3, 4 and 5 you can see how each variable is
declared as an integer. Lines 7 and 8 send the data from the objects to the
variables. Line 10 calculates the addition and outputs the answer into the
variable intAnswer. Line 12 sends the answer to the label object on the
screen. You will notice that the property ".Text" is identified when
accessing data from an object.
Below in Fig. 3.28, you can see we have changed our interface a little and
added more code. A heading is added using a label from the toolbox. The font
is larger and this was done by accessing the Font property.
Three more buttons have been added to allow the user to multiply, minus and
divide. You can see in the code that the buttons are named BtnMultiply,
BtnMinus and BtnDivide (circled). Each button has its own subroutine, and
you will notice that the data type has changed. Now that we have a "divide"
process, we can no longer be working with integers for the Answer variable.
Double is the VB.net version of
decimal number data type.

" der As Object, e As !:vent,;rgs) Handles BtnMultiply.Click

u
n
a
u n ll
+

ll ll � H

Calculator _J *I
Dia dbWuniber-2 As Double
Di111 dblAnswer- As Ooubll!
dblllumber-1 "' txtUumber-1, Text dblNumber-2 = txtUumber-2.Text
dblAn5wer "' dblrlurr.ber-1 • dblrlu1rber2 lblAnswer.Text ..
dblAnswer

u End Sub
TT�

------...._ ----~-·-- ____ _

� i:\'entAr-gs) �ndles BtnMinus .Click

� q
� lblAnswer. Text • dblAnswer

..
End Sub
H
., .,
"
Pdva'l;,t_ Sub
BtnDivide_Cj,ick(sender As

" 41
Object, e As EventAt"gs)
Handles BtnDivide.Click
Oi.a�uble
M Di• dblAnswer- As Double

-
45

n Olli dbltiumber-2 As Double


Oi11 dblAnswer- As Double Solution: ..................... .

• dblNu111berl = txttlumberl. Tl!xt
dblNu111ber-2" txtllumber2.Text
dblAnswer- ., dblrlumber-1 • dblUu111ber-2
H

46 dblNu11berl • txttlumberl. Text


47 dblNu111ber2 = txtllumbl!r2.Text
48
J.9 dblAnswer = dblr/ulllberl / dblrluir.ber-2
50
51 lblAnswer. Text • dblAnswer
52 End Sub
53 End C lass

Page 126
.!lom:l!
forml.vb a .P ss lbxValues. Items .Add( dbl Value)
59

I
1,11,, -··
.:.
62 i Private Sub BtnAddUp_Click(sender As Object, e As EventArgs) Handles

I
a
55 oi• dblValue As Double Olli dblTotal As Double .. 0
BtnAddUp.Click 63

5!J MyFirrtApp
64
- 65 '? For Each i As Integer In lbxValues. Items
r-.. -,:c--
_3
• '-'., BtnAddUp -=---J Solution: .................... ..
•• f Click
+ Calculator
DX
Calculator Add Up Values ��[ + j l
Total is: 15
54 g ����;�� \ub BtnAddlo_Click(sender As Object, e As EventArgs) Handles

��l�J[ZJ1 ;i.7

BtnAddTo.Click :� I End sub _ _ _ _ __ _ _ _

56

57 dbl Value = txtValue. Text


66

dbl Total += i
67
I
68

lbxValues.Items.Add("Total is: " & dbllotal) ..


.,
69
11ext
70
.
71
72
End Sub -�
73

Using Loops with ListBoxes

In Fig. 3.29 above, you can see the program interface has been extended on the right. It allows the user to enter values
using the "Add Value" button. Each value is displayed in the ListBox object. The "Add Up" button adds up all the values
in the ListBox. ListBoxes are really useful. They are simple objects that can hold and display many data items.
The code to add each value is on lines 55 - 58. We need to declare the value as a decimal in line 55, then we input the
data on line 57 from the object txtValue to the variable dblValue. On line 58 we add the value to the ListBox named
"lbxValues". We are using some properties here: "Items" and function "Add."

In lines 63 - 71 we use iteration, or a loop, to add up all the values stored and displayed in lbxValues. This time we
have a new variable dblTotal declared in Line 63 as a double and set to zero. Our loop is called a FOR EACH loop.
This means it will repeat for each item in the list box. Line 65 identifies a counter variable called "i" which identifies
each item in the ListBox, lbxValues. Since this is a loop, we only need one line of code on 57: it adds "i" to the dbl
Total. We have used a compound function(+=) to avoid writing the full code line: dblTotal = dblTotal + i.
On line 69, "Next" returns the loop instruction back to line 65. If there are no more items in lbxValues, it will move to Line
71. This final line of the sub-routine adds the text "Total is:" and the value calculated and stored in variable dblTotal. The
outcome can be seen in the interface.

Conditions & IF Statements

We are going to start a new application. This one will be a pizza ordering app. In this application we will use what we
learned in the Calculator App and add some new objects such as CheckBoxes, RadioButtons, PictureBoxes and introduce
decision control structures using CASE and IF.

In Fig. 3.30 you can see the beginnings of our Pizza App. We are using
an object called a ComboBox to allow the user to select a type of pizza.
There is also an object called a PictureBox which will display an image
that is associated with the selected pizza type.
The images are stored in a folder called "images" which is then stored in
the "Debug" folder inside the "bin" folder which is inside the PizzaApp
folder. This will make the images easy to access from your
code. Objects include: ComboBoxl, txtQuantity, pbxPizza ,
,fo,,.,,,,e,,."owl • Sfleded Pllu Type I � ·]
and btnAdd. The ComboBox has a property called "Items". .._ c:==:i
You can simply type in the list you want to appear in the
CombBox in this property.

PizzaApp > bin > Debug > images

.., C, Seard1 imag

hawaiian margarita pepper vegie

Page 127

--- -
------ --- - -- ------ - ---- ---- Forml.vb .c, X Forml \lb!D�"Jn]
In Fig. 3.31, is code that controls what
J,�.,
happens when a selection is made �14'iip1zuor�A!!_ _
�Piz:z1App
,-
FPLlblic Clas$ Pi:uo de�4pp I ,,.,.,.., ___ _ ��•lr,1li•hie'

cases. The first case is Case 0, the


by the user in the ComboBox. Line 3 identifies the ComboBox 16

name and Selectedlndex. All computer indexes begin at zero. second case is Case 1 etc. You can see our Case for
We have four types of " each selection on lines 4, 13, 21 and 29.
11

pizza (Margarita, Pepperoni, Hawaiian 12 Whatever code we place for each Case, will be
executed if the user makes that case selection.
"
and Vegie) therefore we have four ,.,
1'
"
"
pbxPiz:z1.I11111gelocatior1 • I11agePath
We have created a little mini program in each Case. You can pbxPitza.I111age • riewI,uge
Can 2
" Di. I111agePath As Sti-irig • "irr,ages/hawaihri.jpg"
see they are all " Di• i,.gl As eit,r,ap
Di. r1ewlm1ge As I111ase • I!l'l8t.Frcn,Fiie("i1uges/haw1iiar1.jpg")
h1gl • Hew l!li tfllap(I111agePath)
the same except for the path to the images in the Debug folder. pbxPi?ta,I11ageLocati0r1 • ImegePeth
pbxPit;a.Image • r,ewl•age

l Priv � b b�:::�
ca�, 3
Db1 tmagePath As String• "irrages/\legh.jpg"

.I
;: ,:� c�:: e!:���:�:�;:�;�:::sed(sender As Object, e As :v1mtArgs) Handles
e 01• "'•' •• ""''
Co1rboBO)(l.SelectedindexChang d 01• IiugeP1th As String " "i111gts/ll'.1u·garit11 .jpg"
[>1• J.ingl As Si u.ap Dia ,,,wtm,ge As I"'•St • 111.,ge.Fi-on,File("images/\ltgie.jpg")
Di• newl.,age As lll'lage "I•1ge.FrO<l'File("i.ages/..argarita.jpg")

--
iagl • New Bit01ap(l1111gePath)
pbxPi:::ro.In,ageLoution • I111geP•th
ptucPi:i::::11.lmage • newl1111111e
c pbxPizza.Irr,age • newh1age � End Sub
ue 1 �
Olli I•111gePath As Strins • "hages/pepper.jpg"
01- 1-gl As Bit,-1111 hgl = New 8itisap(lllla11ePath)
DUI newI,,iage As I1111ge • llllage.Fror,:File("in:agu/pepper.jpg") pbxPiz:a.Im,gelocatior, • I111gePath
higl .- New Bitup(Image?ath) t

Each case will access the correct image and display it in the PictureBox; pbxPizza. We are using the same PictureBox
object pbxPizza, so we need to identify the path to the image files as a variable "ImagePath". This means we can replace
the image in pbxPizza each time a new selection is made.

We now need to think about all the variables we need to calculate the cost of the order. In Fig. 3.32, you can see four more
variables are listed under the Public Class on line 1. We have dblPizzaPrice, the price of each individual pizza; intQuantity , the
quantity of each pizza selected; dbl Cost is the total cost of the order of one type of pizza; while finally, dblTotalCost is the total
amount for the full order.

For example if someone orders two Hawaiian pizzas and Vegie pizza:

dblCost = dblPizzaPrice * intQuantity


dblTotalCost += dblCost

These variables are declared outside of the Private sub-routines, which makes them accessible to all the routines and they do not
need to be declared inside the subs. These are now Public Variables. In Fig. 3.32 you can also see some green code on lines 9
and 18. These are called comments. They are included to make the code easier to read. If you use a single inverted comma at
the beginning of a line, it will not be executed. This is a good way of leaving code in your program, but 'turning it off to test other
aspects of the program.

allows for each pizza


Here you can see the comments are identifying the section of code as "Image Display Code". This will be

to be a different price.

handy when we are editing later. You can also see that each Case allocates a value to dblPizzaPrice. This

Public Class Pizz,Orde•App


DUI dblPizzaPdce As Double
Dim strPizzaType As String
Dim intQuantity As Integer

] Public variables
Dia dblCost As Double
Di.ff\ dblTotalCost As Double
:; ref,HP.�Ci!�

1 Private Sub CorrboBoxl_SelectedindexChanged( sender As Object, e As EventAi-gs) Handles ComboBoxl.SelectedindexChanged

1= Select Case Combo Box 1. Sele ctedin dex


e0• , ' ' , ,m i
Cas • , ,,, ''' ''' ' '''' ''' ''' '''''' ''' ''' ''' ···'' ,.,.,,,, ,, I age D splay Code
Margarita
u
DUI Image Path As String = "iff'ages/rr.argarita .jpg"
11
Dim imgl As Bi tfflap
12
Di111 newimage As Image = Image, FromF ile ("images /margarita.
jpg")
u
imgl = Mew Bitma p(ImagePath)
M
pbxP izza. Imagelocat ion = Image Path
15
pbxPizza.Image = newiinage dblPinaPrice = 1S.95
u strPizzaType = "Margarita" Case 1 '' '''' '
'' ''' ''' ''' '' • ''' ''' ''' ''' ' Sets the Price of the Margarita Pizza
u u u H �n n Type

' ' 'm


' ' ' ''' ''' ''' ''' ''' ''' ''' ''' ''' ''' ''' ''' ''' ''' ''' •'' ' '''''' I age Display Code Pepperoni Dim ImagePath As String= "irr,ages/pepper .jpg"
Dim imgl As Bi tll'lap V
M
pbxP izz a. Image ,. newimage
Dim newimage As Image= Image.FromFile("images/pepper.jpg")
M a
imgl = New Bitll"a p(ImagePath)
a Green comments make the code easier to read.
pbxP izz a. Imagelocation = Image Path

'
'''' ''' ''' ''' ''' ''' ''' ''' ''' ''' ''' ''' ''' ''' '' • '' • '' • '''''''' Sets the Price of the Pepperoni Piz::a Type
D
d blP izzaPr ice � 16. 95
D
strPizzaType = "Pepperoni"
ll
u
B
M
Case 2
H
' ni
'' • ''' ''' •'' ''' ''' ''' ''' ''' ''' ''' ''' ''' ''' ''' ''' '' I age Display Code Hawaiian
Oi111 Image Path As String = "images/hawaiian. jpg"
H
TT
Dim imgl As Bitirap
H/
Di111 newlmage As Ill!age = Image, Frorr.file ("images/hawaiian. jpg" )l

Page 128
Here is our clicks
program so far: the BtnAddPizza, the
user selects a pizza program already
·I using the has data allocated
You ordered 2
Hawaian Sub
Total 279
ComboBox, which to dblPizzaPrice
displays an image, and strPizzaType.
sets the name of It reads the
the Pizza intQuantity from
(strPizzaType) and the text box and
the price multiplies it by the
(dbl(PizzaPrice). price.

Youomered3P�ppffllri Sub Total 50 85

When the user

When we send the name of the pizza and the quantity to the lbxYourOrder, we need to write some text
and add spaces between the data. We must always use"&" between text and a variable when sending
to the screen for display. These are added line by line to the ListBox. Each time the button is clicked, it
adds the latest selection and adds the costs for each pizza type. We now need to add up the total cost
of the order. In our Add Your Pizza button we need to add: dblTotalCost += dblCost
"'
ublic Class Pi=:aOrd e App
Dim dblPizzaPrice As Double
Dim strPizzaType As String
Dim intQuantity As Integer
Dim dblCost As Double

Dia dblTotalCost As Double


C, !!fer;;;rc;;;�
Private Sub Coll'boBoxl_SelectedindexChanged(sende r As Object, e As EventA,..gs) Handles Co
mboBoxl.SelectedindexChanged Select Case Combo Box 1. Sel e cte din dex
Case 0
' ' ' · ' ' ' ' ' r s
' '' ''' ''' ' ' ' ' ''' ''' '' ''' ''' ''' ''' ''' ''' ''' ' ' '' ' ' ''' ' It age Di play Code Margarita Dim Image Path As String = "images/n:argarita .jpg"
Dim imgl As Bi tlr'ap
Olli neiYimage As Irrage = I1rage.Fromfile ("irr.ages/margarita.jpg")
imgl = New Bitrrap(ImagePath)
pbxPizza.Imagelocation = ImagePath
pbxPi:zza.Image = newimage
• '
'''' '' • '' • ''' ' • ''' ''' '' • ''' ''' ''' ''' ''' ''' '' • ''' ''' '' •''''' Sets the Price of the Margarita Pizza Type d blP i:zz a Pr ice = 15. 95[
strPizzaType "" "Marg arita"

Case 1
• m D l
, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , •,, •,,, ,, I age isp ay Code Pepperoni Dim Image Path As
String = "irrages/pepper. jpg"
Di• imgl As Bitmap
Dim newlmage As Image "" Image. FromF ile ("images/pepper. jpg")
imgl "" New Bitrrap(ImagePath)
pbxPizz:a, Imagelocation = Image Path
pbxPizza.Image =- newimage
• ' '
• ''' '• • '• • ''' ''' • •' ''' '''''' '·' ''' ''' '' • ' ' '' • ''' ''' ''' '' '' Sets the Price of the Pepper oni Pizza Type d blP izz a Pr ice = 16. 95
strPizzaType = "Pepperoni"

Case 2
' ' 11
, •,, •,, •,,, •, • •,, • •, • • '• • '•' • • • •'' • •' ''' '' • ''' ''' ''' '• • '' '' I age Display Code Hawaiian
S
Di111 ImagePath As tring= "images/hawaiian. jpg''
Dill imgl As Bito-ap
Dim newimage As Image = Image.frorrFile("images/hawaii an.jpg") DUI newlmage As Image = Irr age .FromFile("images/vegie. jpg")
imgl = New Bitmap(ImagePath) imgl = New Bibap(ImagePath)
pbxPizza.Imagelocation "" ImagePath pbxPizza.Imagelocation = ImagePath
pbxPizz a.Image ,. newlmage pbxPizza.Image = newimage
• ' · • • ' ' 'S t t ''' r
• ' • ' • ''' '' '' • '• • • •' '' • ''' • • • '•' ''' ' ''' ''' ' ' ''' ''''' '' e s he Price of the Hawaiian Pizza Type dblPizzaPr ice "' 13. 95 '''' '' • ''' ''' ''' ''' ''' ''' ''' ''' ''' ''' ''' '''''' ''' ''' '' '' '' Sets the P ice of the Vegie Pizza Type dblPizzaPrice = 14. 95
strPizzaType = "Hawaiian" strPizzaType '"' "Vegie"
Case 3 End Select
' ' ' ' ' ' '' r. Ds End Sub
'''' '' ''' ' ' '''''' ' ' ''' ''' ''' ''' ''' ''''''''' ' ''''' '' '' I age i play Code Vegie
Cr•faroance:
Dim Image Path As String = "irr,ages/veg ie, j pg" Priva
te Sub
BtnAddPi::za_Click(sender As Object, e As EventArgs) Handles BtnAddPizza .Click intQuantity z t)CtQuantity.Text
Di.JS imgl As Bitmap

We also need the customer details so we can deliver lbxYourOr der.Items.Add("Y ou ordered" & intQuantity & "" & strPizzaType)
dbleost = intQuantity * dblPizzaPrice
lbxYourOrder, Items .Add("Sub Total 11 & dbl Cost)
the pizza to them. Let's use a new section of the Form When we double-click on the Add Your Pizza button we
to create a complete receipt for the order in a new can enter the code to calculate the costs of the pizza
ListBox. order and display the information in the ListBox
lbxYourOrder.
r,d r_ll'l.s,o;
b

su
Endl :

-
�-- ------------------------------------------- Page 129
Order Your Pizza now!
[,1c
Seeded Ptua T)1)e Delivey�ss

c==J
You ordeted 2 Margaria Sti> Total 31.9 f22 Simo St. Toowoog Cortad Phone
vj
[Peppernn au-, You� 1 Man;ianta Sub Total 1595 [04440565765
You ordered 3 Pepper'OOI Sub Total SO.BS

(DfflPleteYOU"On:ler
DX

Dear'k. Youon:fe.rlotali,
MdYOU"Piua1 S98 7
08v>!redto 22StnnoSt. Toowono
If we have trouble fvidinQ you, we wl cal you

on· 0.U4456576S

:·-i!ft:r!H•n N,me
Private Sub BtnAddPina_Click(sender As Object, e As EventArgs) Handles BtnAddPizza.Click
''''''''''''''' ' ''' ''''''''' '' ''' ''''' ' '
intQuanti ty = txtQuantity. Text ''''''''''' ' ' ' ''''''' ' Dec la res the Quantity variable and reads data in fro11 text box lbxYourOrder .Items .Add("You ordered ' & intQuantity & " " & strPiz.zaType) ·
' ''' ''' ''' .. t • zz ' '' ''' '''
''' · • Writes a line to the list box with quanitity and ph.::a type dblCost intQuanti y dblPi aPrice '' ''' ''' '·' ''' ''' ''' ''' ''' ''' '· ''' '''' '' ''' ' Calculates the subtotal
r. s " " '' ''' ''' ''' ''' ·'' ''' ''' ''' ''' ''' ' ''' ''' ''' s t
lbxYourOrde Item .Add( Sub Total & dbl Cost) '' Di plays the subto al
' ' ' ' ' ' '' '' ''' ''' '' A t F
dbl TotalCost += dblCost '' ' ' ' ' '' ' ' ' ' ' ' ''' ' ''' '''''' ''' ''' ''' ''' ''' ''' ''' ' dd the subtotal to he inal Cost of the Order. end Sub
:lro!fererce�
Private Sub BtnCon:pleteOrder _Click(sender As O bject, e As Even'tA'"gs) Handles BtnCompleteOrder. Click
· ' ' ' R N
• ' ' '· • ·'' ''' ''' ' • ''' ''' '· • ' ' ''' ''' ''' ''' ' ' ·'' ''' ·' • ·'' ''' ''' ''' '''' eads in the arre, Address and Phone.
Din strllame As String "' txtName. Text
Din strAddress As String = txtAddress. Text
Di• .strPhone As String .. txtPhone. Text
· " '' '' ''' ''' ' ' ''' '''
lbxReceipt.Items.Add( "Dear " & strl�arr:e & •, Your order total is: ) ' '' '' Displays the n111te of custoiner
m A } ,,,,,,,,,,,,,,.,,,,,,,,,,,,.,,,,,,,,,, ,,,,,,,,,,,, lC f t A r ' · '
lbxReceipt.Ite s. dd("S" & dblTotalCost Displays the Tota ost o the order lbxReceip .Items.P..ddC Delivered to: " & str dd ess) ·' ·'' '· ·' '''' ' ''' ' ' ''' '' ''' Displays the

address
" ''
lbxReceipt.Items.Add("If we have trouble finding you, we will call you on: & strPhone) Displays the phone contact

End Sub
ass
lend C l _____ _

cleared of all items.


We have nearly finished our Pizza App. So far
it does everything we want it to do: reads in
the data, calculates the data and displays the
results on the screen. However! We have
allowed for every contingency. What if the

: refa,r=:nc;;-.; - ----
user has ordered three Margarita pizzas Private Sub BtnClear _Click(sender As Object, e
when they only wanted two? We need to provide As even dblCost = 0
the user with a button to clear their order and start dblTotalCost = 0
lbxYourOrder.Items.Clear()
again. See Fig. 3.33 where the subtotal and the End Sub
total cost is re-set to zero. The lbxYourOrder is End Class

But wait, there's more! Your pizza store has a special offer. If the Total Cost of an order is over $50 they
get a free bottle of soft drink. This means we need to test a condition in an IF Statement to decide if the
customer gets the free drink. This needs to happen when the order is completed, so let's edit
BtnCompleteOrder. Below you can see the condition is dblTotalCost >= 50. If it is true, the offer is made.
If it is false, the customer will get a different pop-up message.

Now we need to add options for the customer to choose from. If you are offering the user a free bottle of
drink, give them the option to choose which one. This is where we add new objects on the Form that are
invisible until the customer qualifies for the drink.

If dblTotalCost >= 50 Then


'' '' ' '
MsgBox("Your order is over $50! You get a free 500ml bottle of soft drink,") '' ' '' The offer is
,r,ade when the condition is TRUE Else
'' '''
MsgBox("If you order is over $50 you could get a free 500ml bottle of soft drink!") l·tessage when the condition is FAlSE End If

Page 130
Seeded Plua Type Sub Total 15.95
[Margarta

au.,,..;,y c= I
PizzaApp
You -d�
vj Sub Total 14.95
You ordefed 2 Hawaiian
Sub Total 27.9
X
You ordered 1 Marga,ta
[Jame,
Your ordtr Is over S50! You get a free 500ml bottle of soft drink.
Md YourF'tua!
□X
Dear James. YOUf order total 1s·
S58 8

Name
Delivery Pddress
When De!vere<lto: 2 Spmg St the IF statement creates the pop up message box telling the user they get
If we have trouble fiidiig you. we� call you on 04045�6
F,.e Otange Drink I

[2 Spnng St Contact Phone


a free drink, the program will make three
RadioButtons visible on the Form. [0404555666

The RadioButtons need to be in a GroupBox. You


can find this object under "Containers" in the Complete YOU" Order

Toolbox.
To add an action to a RadioButton just double click
Free Orn Options
on it. We can then send the drink type to lbxReceipt. 0 Lemonade
0 Cola
0-it
@�]

n If dblTofalC:ost >= S0Then

M MsgBox("Your order is over J50 I You get a free 500ml bottle of soft d rink.") '' ''' • '' ''' The offer is made when the condition is TRUE
ll9
� gbxfreeDrinkOptions.Visible = True
� rbnCola.Visible = True
H rbnlemonade.Visible = True
rbnOrange.Visible = True
� Else
MsgBox("If you order is over $50 you could ge t a free 500,nl bot tle of soft ddnk! ") '' ''' Message
H
M when the condition is FALSE End If

"
H
ll ____ 8 Private Sub BtnClear _Click(sender As Object., e As EventA.rgs) Handles BtnClear .Click dblcost =
0
dblTotalCost = 0
lbxYourOrder. Items .Clear()
U2 lbxRec eipt. Items. Cl ear ()
U3 End Sub
U4
us :) refe:rerc;;�
U6 Private Sub RbnLerr-onade_CheckedChanged(:s:ender As Object) e As EventA. rg.s) Handles
U7 rbnlemonade.CheckedChanged lbxReceipt.Items.Add("Free lemonade Drink!")
ua End Sub
U9 ,: refer:rce:
ll0 Private Sub R bnCo la_CheckedChanged(sender As Object., e As EventArgs) Handles
ill rbnCola.CheckedChanged lbxReceipt.Items.Add("Free Cola Drink!")
ll2 End Sub
ll3 : rele,rer'CE5
ll4
us E Private Sub RbnOrange_CheckedChanged(sender As Object, e As i:ventArgs) Handles
ll6 rbnOrange.CheckedChanged lbxReceipt.Items.Add("Free Orange Drink!")
End Sub
ll7
ll8
E n
'--"-.;;....un -"lwlc.. _ _d Class

All we need is a Quit button and we are done. A very simple function - see below. G refer2rce:;

Private Sub BtnQuit_Click(sender As Object, e As EventA�gs) Handles BtnQuit.Click


121
Close()
122
End Sub
123
End Class
124

Don't forget there are plenty of VB tutorial websites online. A good starting
place is: https://www.vbtutor.net/vb2019/vb2019tutor.html

Page 131

You might also like