If you can't read please download the document
Upload
vuongnguyet
View
215
Download
0
Embed Size (px)
Citation preview
_
ObjectivThe mainto use MTerminoWhat is aA compuperformeWhat is aA prograC++, Jav
Kpr
O V S
S P C
Methods
P
O
D
Lab 4: G
ves: n objective oicrosoft Visu
ology a computer puter programed by a compa programmiamming lan
va, C#, VisuaKeywords (R
rogrammingOperators -- SVariables -- U
yntax Set of rule Similar to
strictly fo If even a
tatements --rocedures --
Comments (R Ignored w
programm In Visual s of Programrocedural
Construct Each procObject-Orient Uses real- Objects h Objects al
Departme
Mathema
Getting Sta
of this lab isual Studio .N
program? m is a set of iputer. ing languagguage is a al Basic. A p
Reserved Wog language, cSpecial symbUsed to store
es o the syntax
ollowed single syntax Instructions
- Set of progrRemarks) when the p
ming statemeBasic, any s
mming
ted as a set ocedure is a seted -world objecave data elemlso perform
ent of Coand
atical Sci
arted with
s to understaNET to creat
instructions
ge? special lang
programmingords) -- Worcannot be usbols that pere data in mem
x (rules) of
x error appes made up oframming sta
program runents statement tha
of procedureet of instruct
cts such as stments calledactions
mputer
iences
h Visual B
and how create VB .NET
for a problem
guage used tg language crds with speed for any orform varioumory, named
a spoken l
ars in a progf keywords, atements tha
ns, help hum
at begins wit
s (operationations
tudents, trand attributes
CSIntro to
ScieVisual
asic .NET
ate Windowapplications
m to be solv
to write comconsists of: ecial meaninther purpose
us operationsd by the prog
language, su
gram, it will variables, an
at perform a s
man reader
th an apostro
al, functiona
nscripts, and
Unit 2: Visual B
S 1408 o Computeence with Basic .NE
T Program
ws applications.
ved or a task
mputer prog
ng that makee s on data grammer
uch as Engl
not compilend operatorsspecific task
understand
ophe (')
al units)
courses
Basic .NET, pages
er
T 4
mming
ns and learn
or an event
grams such
e up a high-
ish, but mu
e or executes. k
d the purpos
s 1 of 13
4
n how
to be
as C,
-level
ust be
se of
Example T C D
d A A F T
T L B
Event Dr T A
V A
The ProgStep 1:
C F
Step 2: V
uStep 3: D
e of an ObjeThis is a VisuContains dataData, such a
etermines thActions, suchA form is an
orm elemenThis form has
Two T Four L Two B
The value disLeft button teButtons have
riven ProgrThe GUI envAn event is an Clicking a Keying inVisual Basic A program ca
gramming P
Clearly defineor example,
Purpose: T Input: Nu Process: M
gross pay Output: DVisualize theuser interfacDetermine th
Control Form1 DTextbox1 NTextbox2 NLabel1 DLabel2 DLabel2 DLabel3 DButton1 GButton2 E
ect ual Basic GUa and actionsas Hourly
he appearanch as Calculatobject that cts are objects: TextBox conLabel controButton contr
splayed by a ext propertymethods att
ramming: Eironment is n action thata button (a Cn a TextBox controls are
an respond to
Process of D
e what the pthe Wage C
To calculateumber of houMultiply nu)
Display a mee application
ce he controls n
Name Default NumberBox1 NumberBox2 Defualt Defualt Defualt DisplayLabel GrossButton ExitButton
UI object cals Pay Rate,
ce of form obte Gross Paycontains othets called con
ntrols ols rols
control is hey is Calculattached to clic
Events event-drivent takes placeClick event)
(a TextChacapable of d
o an event if
Developing a
rogram is toCalculator pre the users gurs worked, humber of hou
ssage indican running on
needed
A form to holAllows the usAllows the usDescription foDescription foDescription foDisplays the gWhen clickedWhen clicked
led a form
is a text pbjects y, is a methoder objects sutrols
eld in the texte Gross Payck events
n within a pro
anged event)detecting maf the program
an Applicat
o do ogram:
gross pay hourly pay rurs worked
ating the usern the compu
Dd these controls er to enter the numer to enter the houor Number of Houor Hourly Pay Rateor Gross Pay Earnegross pay, after thed, multiplies the nud, terminates the ap
property tha
d that determuch as button
xt property oy
ogram
) any, many evmmer writes
tion
rate by hourly p
rs gross payuter and desi
Description
mber of hours workurly pay rateurs Worked TextBoe TextBoxed Label e btnCalcGrossPayumber of hours wopplication
Unit 2: Visual B
at
mines how thns, text boxes
of the contro
vents an event pro
pay rate (re
y ign its
ked.
ox
y button has been corked by the hourly
Basic .NET, pages
he form reacs, and labels
ol
ocedure
sult is the u
clicked y pay rate
s 2 of 13
cts s
users
Lab 4: Getting Started in Visual Basic .NET, page 3 of 13
Step 4: Define the values of each controls relevant properties Control Name Text ForeColor Font Size Others Form1 Default Wage Calculator Default None Size: 310, 315 Textbox1 HoursTextBox None (blank) Default 10 Size: Width: 100 Textbox2 RateBox None (blank) Default 10 Size: Width: 100 Label1 (Default) Number of Hours Worked Blue 10 (Default) Label2 (Default) Hourly Pay Rate Blue 10 (Default) Label3 (Default) Gross Pay Earned Blue 10 (Default) Label4 DisplayLabel $0.00 Red 10 MinimumSize: 100, 23 BackColor: Pale Yellow Button1 GrossButton Calculate Gross Pay Blue 10 Size: 100, 50 Button2 ExitButton Exit Red 10 Size: 100, 50
Step 5:Determine the event handlers and other code needed for each control Method Description
GrossButton_Click Multiplies hours worked by hourly pay rate
These values are entered into the HoursTextBox and RateTextBox
Result is stored in DisplayLabel Text property
ExitButton_Click Terminates the application
Step 6:Create a chart or pseudocode version of the code
Step 7:Check the code for errors
Read the chart and/or pseudocode Step through each operation as though you are the computer Use a piece of paper to track the values of variables and properties as they change Verify that the expected results are achieved
Step 8:Use Visual Basic to create GUI (the forms and other controls identified) in Step 4 This is the first use of Visual Basic, all of the previous steps have just been on paper In this step you develop the portion of the application the user will see
Step 9:Use the chart or pseudocode from step 6 to write the actual code This is the second step on the computer In this step you develop the methods behind the click event for each button Unlike the form developed on step 8, this portion is invisible to the user
Step 10:Attempt to run the application - find syntax errors Correct any syntax errors found Syntax errors are the incorrect use of an element of the programming language Repeat this step as many times as needed All syntax errors must be removed before Visual Basic will create a program that
actually runs
Wage Calculator Application
Gross Button Click Event: Retrieve text from HoursTexBox and assign (store) to Hours variable. Retrieve text from RateTexBox and assign (store) to Rate variable. Multiply Hours and Rate and store the result in Gross variable. Display result (Gross) in DisplayLabel
Exit Button Click Event: Close the application.
Step 11:
Task 1: RIn this taActivity you will
1. C2. F
3. W
4. Eto
5. S
6. ItE
Run the ap Run the p Check th Incorrect Correct a Repeat th
Running a Vsk, you will 1.1: Downldownload is
Click on the lFile Downloa
Windows Ex
Extract Como locate the lelect a desti
t will bring Extract butto
pplication usprogram wit
he results to bt results are any runtime his step as m
VB Applicalearn how aoad Wage C
s a zip file. Slink Wage Cad window w
xplorer will
mpressed (Zlocation to saination wind
you back on. You shou
ing test datath a variety obe sure that referred to aerrors found
many times a
ation a VB applicaCalculator aSo, follow thCalculator 2will appear.
appear. Clic
Zipped) Foldave the appldow will app
to Extract uld have the
a as input of test data they are cor
as a runtime d as necessary
ation looks liapplication f
hese steps: 2008 or WagThen click o
ck on Extrac
der windowication. In thpear. Then c
Compresseapplication
rrect error
ike and how from my we
ge Calculatoon Open but
ct files unde
w will appearhis case, the click on OK
ed (Zipped)saved on yo
Unit 2: Visual B
it works. bpage. Note
or 2010. tton.
er the menu b
r. Click on Blocation is ybutton.
) Folder wour USB driv
Basic .NET, pages
e that the file
bar.
Browse byour USB dr
window. Clicve.
s 4 of 13
e that
button rive.
ck on
There are1)
2)
Figur
After youMicrosofsection, awas last section shline Page. Bu
Fig
Activity
CalculatMicrosoopen Wa(IDE) wi
e two ways tFrom the Vdouble clickFrom the APrograms cchoose MiMicrosoft Vin Figure 2.
re 1: Menu fro
u started Visft Visual Stuas shown in modified. U
hould be em
ut if you w
gure 3a: Visua
1.2: Start
tor on your ft Visual Stage Calculaill appear. It
to start VisuaVisual Studiok on the icon
All Programcommand icrosoft ViVisual Stud
om Start butto
sual Studio .udio like in Figure 3b, itUsually the
mpty. To star
want to open.
al Studio .NET
VB .NET. .
USB drive.tudio Solutiation applicawill look as
al Studio .NEo .NET iconn.
ms command
sual Studidio .NET co
on
.NET, a VisuFigure 3a wt will show afirst time y
rt a new VB in the R
n an existin
T Start Page
On the StOpen Proj
. Double onon file. Theation. The V follows
ET 2008 n , high
d, click on Sfrom the Sto .NET c
ommand
ual Studio .Nwill appear oa list of exisyou start Viproject, clicRecent Projng project,
F
tart page, cject window
n the folder. n select the Visual Studi
Lab 4: Getting
hlight the ic
Start button tart menu aommand
Figure 2: A
NET Start Pon the screensting projectsisual Studiock on Projecjects sectionclick on Pr
Figure 3b: Re
click on Prw will appea
You shouldfile and clicio Integrate
g Started in Visual
con then pre
anas shown in
All Programs
Page with a tn. Under thes and the dat
o .NET, the ct n in MS Visroject on
ecent Projects
oject on ar. Locate t
d seeck on Open ed Developm
Basic .NET, page
ess Enter k
nd then selecn Figure 1.
in menu as sh
title Start Pae Recent Prote that the prRecent Pro
in the Crsual Studio
n the Open:
Section the Open:
the folder W
button. Thisment environ
e 5 of 13
ey or
ct All Then
n the hown
age ojects roject ojects reate: Start
: line
: line Wage
a s will nment
Activity combinat
Task 2: CIn this taActivity environm.NET app
.NET Stasteps:
1. MTpr
2. N
Yso
3. C4. T
1.3: Run aption of value
Create the Fsk, you will 2.1: In this a
ment (IDE) toplication pro
art Page, a N
Make sure thaTemplates: s
roject to be cName the you
You should something sim
Click on BrowTo complete
form view
pplication Wes for the hou
First Appliclearn how toactivity, youo create and oject as Lab4
in ReNew Project
F
at under Prosection seleccreated is a Wur project in
ee the defaumilar. Renamwse button tcreating Lab
w
Wage Calcuurs worked a
cation o create a VBu will learn hsave a VB .N
4. Click on Pecent Projecwindow wil
Figure 3: New
oject types:ct Windows Windows apthe Name te
ult name appeme it as Lab4to change deb4 project, ju
lator by preand the rate
B .NET applhow to use thNET Windo
Project lincts window all appear as s
w Project dialo
section VisuForms App
pplication in ext box
ears in the N4 by typing oestination to ust click OK
essing F5 oras well as ch
lication. he VB .NETows applicatink under Cras in Figure 3shown in Fig
og window
ual Basic lanplication. Th
VB .NET.
Name textboxover the defayour USB d
K button
cod
Unit 2: Visual B
r clicking onheck on both
T Integrated Dion. You wil
reate: 3b in MS Vigure 4. Then
nguage is sehis is to indic
x as Wisdowfault name. drive.
.
de view
Basic .NET, pages
n . Try seh buttons.
Developmenll call your V
isual Studio n follow thes
lected. Undecate that the
wsAppliction
s 6 of 13
everal
nt VB
se
er
n1 or
After theMicrosofand you a
Note thatthat you
Figure 5: L Before ycompone
Tshth
Mu
e OK buttonft Visual Baare ready to
Figure 4
t after you ssaved as foll
List of folders
you go on tents. Title Bar Thows the namhe following
Menu Bar Tsed to perfor
n in Step 4 iasic .NET [dcrate a Wind
4: Visual Basic
save your aplows:
s and files crea
to create a
he Title Barme of the cu
g figure.
The Menu Brm any activ
is clicked, Vdesign] Fodows applic
c .NET enviro
pplication, th
ated by VB .N
VB applica
r is the colorurrent projec
Bar as shownvities related
Visual Basicorm1.vb [Deation.
nment window
here are 3 fo
NET
Lab bin obj My Fo
file Fo Lab Lab
Op
ation, you sh
red bar at thect (in your ca
n in the figud to project o
Lab 4: Getting
c .NET IDE esign] as sh
w
folders and 5
b4 folder n folder j folder y Project folorm1.Designe) orm1.vb (Visb4 (Visual Bb4.vbproj (V
ptions)
hould get fa
e top edge oase the title
ure below shor appearance
g Started in Visual
window wihown in Figu
5 files create
der ner.vb (Visu
sual Basic SoBasic ProjectVisual Stud
familiar with
of the VB .Nshould be L
hows the mee of the wind
Basic .NET, page
ith titled: Laure 5 will ap
ed at the loc
ual Basic So
ource file) t) dio Project
h VB .NET
NET IDE winab4) as show
enu of commdow.
e 7 of 13
ab4 ppear
cation
ource
User
IDE
ndow wn in
mands
FinonItnpritfo
Vshclfiopcow
D
shclficoy
T
qu
SEditasSsuCqu
File Menu n Figure 7 cn the File ct contains thew project oroject or fitem, open orms,
View Menu hown in Figlicking on tile menu. It cpening any omponents s
window.
Debug Menuhown in Figlicking on thile menu. It compiling, dour applicati
Tool Bar Tuick access t
Solution ExpExplorer win
isplays a hietems contains Solution R
Solution Expuch as View
Code windowuick access t
The File mcan be openommand in e commandsor file, openiile, add neand close
The Vgure 8 can the View cocontains the window of such as toolb
u The Degure 9 can he Debug cocontains the debugging, ions.
The tool bar to often used
plorer Windndow as sherarchical lisned in a projResource Wiplorer wind
w Code -- w and Vieto the Form
menu as showned by clicki
the file mens for openining an existiw or existisolution, sa
View menu be opened
ommand in tcommands VB .NET IDbox, propert
ebug menu be opened
ommand in tcommands executing
as shown id commands
dow The Shown in Figst of projectsject. It also rindow. Tool
dow containquick accesw Designerwindow.
wn ing nu. g a ing ing ave
as by the for DE ties
as by the for of
in the figures in the Menu
Solution gure 10 s and all referred l bar of
ns icons ss to the r --
Figure
Figure
Figure 8
e below shownu bar.
Figure 9:
Unit 2: Visual B
e 6: The File M
7: The View m
8: The Debug
ws the icon
Solution Expl
Basic .NET, pages
Menu
menu
Menu
ns that provi
lorer Window
s 8 of 13
des a
w
Lab 4: Getting Started in Visual Basic .NET, page 9 of 13
Toolbox Window The Toolbox window as shown in Figure 11 contains a set of controls that can be placed on a Form window to produce a graphical user interface (GUI goo-ey). The toolbox can be opened by choosing the command Toolbox in the View menu.
Figure 10: The Toolbox Window
Properties Window The Properties Window as shown in Figure 12 contains the list of property settings for the selected Form or control. Its properties can be modified from the Properties Window.
Figure 11: The Properties Window
Form Window The Form Window as shown Figure 13 in the From1.vb [Design] window as shown in Figure 14 is used as a window to hold desired control items during the design process to produce a graphical user interface. By default the Form Window appears first in the VB .Net IDE with a title as Form1. The title and the size of the window can be modified through the Properties window.
Figure 12: Form Window
Figure 13: Form1.vb [Design] Window
You should get familiar with these components, so you can use them in the next activity. Task 3: Adding Controls in the Form In this task, you will learn how to add Label and Button controls into the VB .NET Form. Activity 3.1: Change the title from Form1 to Hello by following these steps:
1) Click on Form1 window to make the window active or chosen. 2) Look for Text property in the Properties window and click on it. 3) Change the text from Form1 to Hello by typing the word Hello and press enter.
You shouform is applicatio
Activitypixels by
1) 2)
Activity steps:
1) 2)
Activity (Hint: loo
Activity ClicHel
Note that
Activity Activity
1) 2)
3) CreH
Activity from 7.8
1) 2)
3) 4) Or
2)
uld see the tthe name oon.
y 3.2: Resizey following tClick on SizChange its w
3.3: Add a
Click on LaClick inside
3.4: Modifok for text in
3.5: Changeck on NamelloLabel. t the name o
3.6: Change3.7: ChangeSelect TextAClick on thfigure below
Click at the teplace TopL
HelloLabel. 3.8: Changeto 22 and reClick on FoClick on thelist of Font Change the Change the
After the Fselected from
title changedof title bar
e the width athese steps: ze property inwidth (the fir
Label contr
abel in the Toe the Hello wfy the Labeln Propertiese the name oe property in
f a control is
e the Mimime the text aligAlign from te button
w.
top center bLeft in the
e the size anegular to bolont property e + icon properties wSize to 22. face Bold to
Font properm 1), an ellip
TopLe
MiddleLe
BottomL
d from Formof the win
and height o
n the Properrst number)
rol from Too
oolbox windwindow. A la
l control in window.)
of Label1 conn the Proper
s used as a v
mumSize propgnment (Texhe Propertie
a guided
box for MidTextAlign b
nd the face od, respectivein the Prope
will expand a
o True.
rty in the pses button
M
Bo
eft
eft
eft
m1 to Hellondow that a
of Hello win
rties windowto 400 and h
olbox windo
dow. abel with a te
Activity 2.3
ntrol to Hellrties window
variable that
perty of HelxtAlign propes window.d template w
ddleCenter abox. The w
of the font fely. There arerties window
in front oas shown in t
Properties will appe
TopCenter
iddleCenter
ottomCenter
on the title appears whe
ndow or For
w. Make sureheight to 250
ow in Hello
ext named L3, Label1, t
loLabel. w and chang
will be discu
lloLabel to 1perty) from T
with boxes
alignment. T
word Hello w
for HelloLabre two ways w.
of the Font pthe right figu
window is ear.
TopRight
MiddleRi
BottomR
Unit 2: Visual B
bar, Note then you run
rm1 window
e the Hello w0.
o window by
Label1 will ato display th
ge the name
ussed later o
150, 40.
TopLeft to M
will appear
The value Mwill be at t
bel control to do this.
property, a ure.
t
ight
Right
asic .NET, pages
hat the title oor execute
w to 400 and
window is ac
y following
appear.
he text as H
e from Labe
on.
MiddleCente
as shown i
MiddleCenterthe center o
10 of 13
of the e this
d 250
ctive.
these
Hello!
el1 to
er.
in the
r will of the
3)
4)
5) Activity similar to
Activity Activity Activity Activity Activity default b
1) 2)
Fig
3)
Activity Activity Start comkeyboardFigure 1window, or progra Task 4: AIn this tain Task 2Activity
1)
Click the elappear. Replace Regbox. Replace 8 w3.9: Add a
o adding the
3.10: Chang3.11: Chang3.12: Chang3.13: Chang3.14: Chanlack to blue.Click on FoClick on theappear as sh
gure 14 a: Cu
Select blue in blue.
3.15: Resize3.16: Run th
mmand fromd. The windo6. Note thatnothing wil
am the Engli Adding an E
ask, you will2 is clicked, t4.1: AddingDouble-clicknamed Engl
lipses button
gular with B
with 22 in theButton conLabel in Ac
ge the text o
ge the name
ge the font si
ge the font st
nge the Fore.
oreColor proe button
hown in Figu
stom Color Pa
color from t
e EnglishBuhe Hello VB
m the Debug ow with titlet if you clicll happen. Thish button w Event Procel learn how tthe word He
g a code to Ek on EnglishlishButton_
n . The F
Bold in the F
e Size textbontrol from Tctivity 2.3.
f the button
of the Buttoize of now th
tyle of the EeColor (fore
operty in the a color b
ure 15.
allet Figure
the Custom
utton to 120,B .NET appl
menu or pree Hello will ck on Englihe reason is
what to do. edure or Coto add an evello in the lab
English buttoh button, the_Click as sh
Font dialog w
Font style tex
ox or select 2Toolbox wind
in Activity 2
on1 to Englishe EnglishB
EnglishButtoeground colo
Properties wbox with thr
15 b: Web Co
tab. The wo
, 40.
ication by chess F5 key frappear as sh
ish button inyou have no
ode to Makevent procedubel will be don. e Code windhown in Figu
Lab 4: Getting S
window as s
xtbox or sele
22 in the list dow in the H
2.8 from BuishButton. Button to 12on to Bold. or or text co
window. ree tabs: Cu
olor List
ord English
hoosing from the hown in n Hello ot coded
e a Control ure or a codedisplayed in
dow will opeure 17.
Fi
Started in Visual B
shown at the
ect Bold in t
box. Hello Form
tton1 to Eng
.
olor) of Eng
ustom, Web,
Figure 15 c: S
in the Engli
Perform a te so when thblue.
en with the e
gure 15: Hello
Basic .NET, page
e right figure
the Font styl
window. Th
glish.
glishButton
and System
System Color
ishButton no
task he English b
event proce
o Application
11 of 13
e will
le list
his is
from
m will
List
ow is
button
edure
2)
H by
sh Pr E Activity choosingkey fromappear as
Activity Task 5: AIn this tamore BuActivity following
1)
2)
Figure 17: Co
Insert the fo
HelloLabel.FHelloLabel.T
y typing thehown belowrivate Sub En HelloLab HelloLab
End Sub
4.2: Run g Start commm the keybos shown in F
4.3: What w
Adding Mosk, you will tton controls5.1: Modify
g descriptionAdd two BSpanishButrespectivelyArrange all
ode Window o
ollowing cod
oreColor = CText = "Hello
above code. nglishButton_ As S
bel.ForeColorbel.Text = "H
the Hello mand from toard. The wFigure 17.
will happen i
re Buttons modify the Hs.
fy the Hello n.
Button controtton with they. the controls
Figure 1
of Form1 with
de in the even
Color.Blue o!"
e inside the p
_Click(ByValSystem.EventAr = Color.BluHello!"
VB .NETthe Debug m
window with
if you click o
Hello VB .N
VB .NET
ols and Name text shown
Buttons and
18: Hello VB.N
the event pro
nt procedur
procedure Ensender As Sy
Args) Handlesue
T applicatiomenu or preh title Hello
on English b
NET applicat
application
me the two n as French
d Label as sh
NET Applicat
ocedure named
re EnglishB
nglishButtoystem.Objects EnglishButt
on by ess F5 o will
F
button in He
ation that cre
that created
Button conh in red and
hown in Figu
tion Design Fo
Unit 2: Visual B
d EnglishButt
Button_Clic
on_Click bt, ByVal e ton.Click
Figure 17: Hel
ello window?
eated in Task
d in Task 3
ntrols as Frd the other S
ure 18.
orm
asic .NET, pages
ton_Click
ck
efore End S
llo Application
?
k 3 by adding
according t
renchButtonSpanish in g
12 of 13
Sub as
n
g two
to the
n and green,
Add the1.
2.
3.
Activity
e appropriateWhen the FFigure 19. When the SpFigure 19. When the EFigure 19.
5.2: Test yo
e event proceFrench butto
panish butto
English butto
Figure 1
ou Hello VB
edures or con is clicked,
on is clicked
on is clicked
19: Hello VB .
.NET applic
des to the F, the label w
d, the label w
d, the label w
.NET Applicat
cation by run
Lab 4: Getting S
FrenchButtonwill display B
will display
will display
tion at Run T
nning it.
Started in Visual B
n and SpaniBonjour! in
Hola! in g
Hello! in
Time
Basic .NET, page
ishButton son red as show
green as show
blue as show
13 of 13
o that wn in
wn in
wn in