chap 3 and 4
chap 3 and 4
.End-If
Else
<Block for false evaluation of Boolean_expression_l>
End If
....,
, 11 I
Con trol s~
True
True
State ments False
True
t'
'If!:_
Statem ents
Statem ents
·, .:,--·
>+-- - - - -~ Statem ents
...•I .- . . ..
~-- '~:~>
~ ~-
I ' ,· ~ .;·i,;-:: .
·.,
:
Staternen ts
.. 1.-:a_.,,•.•."·
.~:- • . ·~ ....' \ "_.
111
control StTUCture.s 1 . .
I
f con sol e bas ed mo du e com pns mg abo ve cod e sni ppe t 1.
t O ---. s as follows .
...... - - - - - - - - - - - - --
The out pu
[i] file:///C:/Users/lndu Arora/AppData/Local
En ;: er Ma rk s
56
Grade is C
ure
3. 1.5 Sel ect ... Case Sel ect ion Str uct
re. ft
.. . Cas e Sel ect ion stru ctu re is a~ ,ll i,:p gtl]. dec isio n ma kin g stru ctu
The Select ff.
the re are mu ltip le con diti ons . I_t wo rks ~e I(...El.§~if.. . Else ...End
is preferred wh en of
en .~ ser
.. ? ee~ ~.~ ~ H~o_e:pa r~ val1:e _0 ~ a smgle .Y~,abl e wit h a set
.81.ltit is use ~ wh y
.el~ ~t.. .C~ ~e- ~ta te~ e11:-t ,.g) 1Q~ s a van able to be tes ted for equ alit
~ s. li!; U~~--a_.S e. .
wh ere eac h val_,.. ue 1s cal led a cas
'a ainst a list of val,.ues . -,.; - ...._ .~-· ---: :--:-- -- ---
res sio n. The
g
Sel ect .. . Cas e sta tem ent is foliowed by a var iab le or an exp
--- fiie ich may be
ion mu st eva lua te to any of the ele ~en tar y dat a typ e in VB.NET wh
express t, SBy te, Sho rt,
lean , Byt e, Ch ar, Dat e, Do ubl e, De cim al, Int ege r, Long, Ob jec
Boo by mu ltip le cas e
gle, Stri ng, Uin teg er, UL ong and US hor L Thi s sta tem ent is foliowed
Sin sta nt or literal
The val ue of a 'cas e' mu st be a con
statements along with the ir val ues . the Select ...Cas e
it sho uld be of sam e daJ :a..t.¾W !-..as...th_e,...\[,8..0a.Pk_gr exp res si<)!1 in s.
and d, they are sep ara ted by com ma
le exp res sio n cla use s are use
statement. If mu ltip ect
also han dle ran ge of val ues . The gen era l form of a sim ple Sel
~ em ent can
t is sho wn as foliows.
...Case along with VB.NET code sni ppe
Syn tax
on>
Select Case <test expression or conditi
Case <expression-I>
statement(s)
Case <expression-2>
statement(s)
Case <expression-3 >.
[Case Else
Statements]
End Select
_ Code-snippet
Dim grade As String
grade=txtgrade.Text
Select Case grade
Case "A"
Labe1I.Text=">= 90%"
Case "A-"
Labell. Text=">= 80% and <90,,
control Stn«:tJ.tres
Case "B"
Labell .Text=">= 70% and <80"
Case "C"
Labell .Text=">= 60% and <70"
Case Else
Labell.Text="< 60%"
End Select
The variable or expression specified with Select ...Case statement is evaluated. The
evaluated value is then matches with the values specified for different cases. When the
match is found, a block of code associated with that case is executed. _The Case Else
-~ ock,is,.Q~ti.9nal,.andit.,mlj,_st..appear_ru..,..tbe el)d..Pf _the Sel~ct_..._._.Case...lt i§....e xecuted only'
if no case value matches with the value of the Select ... Case variable or expression. So,
the Case Else block handles all values that are not explicitly handled by one of
the case blocks. So, it provides an easy way to execute different blocks of code based
on the value of the variable or expression. The flow of Select ... Case structure is shown
in Figure 3 .4 diagrammatically. :·,
Figure 3.4: Select ...Case Structure
Next-Statement
-
3.1. 6 Imm edia te IF (IIF)
In VB.NET, IIF() is a func tion . It retu rns one
of two obje cts, dep end ing on the
VB.NET, but it is not par t of Common
evaluation of an exp ress ion. It is use d in
The gen eral form of an IIF stat eme nt
Language Run time . So, it sho uld be avoided.
follows.
along with VB.NET code snip pet is sh_own as
Syn tax
Fals ePar t As Object) As Object
llF{Expression As Boolean, TruePart As Object,
Code Snip pet
MessageBox.show(IIF{ 10 > 20, "True", "False"))
3.2. 1 The D~ ... Whil~ Loo p•' Gt~dJ,'~ Tm~ ~o ~ 0,-.t ~rl) J~ .
--;;o~p: - = - - ~ : - - - - : - - - - - - - - L
.__Lo
·
-- -- -- -
··
Lo~o'.!'.p~Wh~~il=e_<: ::c~o~n~d~iti~·o~n~>:_
d · If the
If. the con ditio n eva luat es to true , the bod y of the 1oop 1s exe cute agam .
.
term inat es and the prog ram cont rol moves
cond1t10n eva luat es to false , the enti re loop
~
,c,ocrolsiruct•'"' at fo llo ws th e Do ...
.
While. loop. The diffe rences m th wo rki n~ of
st at em en t th . pre-test (Do Co _e_
the next in pr e- te st an d po st -t es t sc en an os 1s th at op-body d n~iti on ...WhiJ e)
to bile ut es th e lo epending u pon th e
th e co nd iti on fir st an d th en ex ec . ) ex
pq ... W . po st -t es t (Do ... While Co nd iti on ecutes the Joop-b ody
a1uates e co nd iti on . W hi le , . . . de pe ndin u O
ev t of th on . Th e loop 1s co nt in ue d
ul
d then evaluates th e co nd iti n res~ t of
res s ca nld he _t ep :n in ated any time Wl~th Pth e Exn Do
, th es e loqp f
first an d'tion. However fl o .. . ~ il
.
e
le
(pre-test) an d Do ... Whi (pOst test)
_
the co n T~ e ow o D
en t ip§!P e th~g >.g e.....d.. Figure 3. 6 respectively.
I
In iti al iz at io n
· Fa ls e
Tr ue
(E nd of lo op )
W hi le lo op bo dy
St at em en ts
Loop (Post-test)
Figure 3.6: Do... Whlle
Initialization
Do while lo op body
False
(End of loop)
St at em en ts
rs from 1 to 10
· console
Now' write 1· .wn m od ul es in VB.NET to pr in t nu m be
• ap p icat
Usmg Do ... Wh 1.1 . both p t sc en ar io s. Pr oj ec t 3. 3 sh ow s th e so ur ce
• VB.NET.e In
coct em re- es t an d po st te st
- ◄
Cmttrol StTketJt~
\
Do...1"dle(Pre-te1t)
Do...Whlle(Po1t-te1t) --
~
Module Mod_dowhile_post
Module Mod_dowhile
Sub mainl) Sub main()
~
In iti al iz at io n
Tr ue
· False
(End of loop)
Until loop bo dy
ts
,.___--Next St at em en
In iti al iz at io n
U nt il lo op -b od y -
(End of lo op
N ex t S ta te m en ts
- _ _ _t..
..J
·
om 1 to 10
Now ·
nsole 1· • ul es in VB N ET to pr in t nu m be rs fr
• ' wnte co. ap p 1cat10n m od . oj ec t 3. 4 sh ow s th e
so ur ce
usmg Do unt'l m b th te st sc en ar io s. Pr
"• 1 o pr e- te st an d po
st
code in VB.NET.
- Project 3.4: Printing 1 to 10 Numbers using Do ...Untll
Cmltro( Stntcture.5
6
7
0
u
G
10
For... Next loop is preferably used when the number of repetitions is known before
hand . . 1s oop starts ~th the Keyword 'For"'. 'Ifs\jndex-var~ alsocafie~01
variable s it controls the iteration of the loop-body. Index variable is initialized onlY
o ce in the beginning. After initialization, condition is evaluated. If condition evaluates
to false, the loop is terminated, otherwise loop-body is executed. After executing Joop·
body, index variable is incremented or decremented with step-value.
~
. . EID
eontrol structures of every iterati·on · If th e conditi ·
. . also eva lua ted at the beg mn mg on 1s
dittondyis exe cut ed. If it is false, the loop is terminated d pro gra m
The con b is 11 . th e For ... Next loop E an the
fi
loop- to the nex t-st ate me nt o owmg · ventually the
,..., 1e the p b . ' .
aves O
e. Oth erw ise the loo
v- '
ntrol m N xt loop sho uld bec. om e fals . . ' eco me s infi nite
co . of For... e t loop sta tem ent 1s sho wn m Fig ure 3.9 diagrammaticallY an d the·
onditIOI1 Nex d . .
c of For ..• t loop along wit h VB. NE T co e sni ppe t 1s shown as follows .
The floWof For ... Nex
syntaJC
[Step ste p-v alu e]
syntax ter==startNu mb er to end Nu mb er ,.,-
For coun .
sta:temeQts_
Next
code snippet
ter as Integer rem~erit val ue is one
Dim coun t 10 , by def aul t ste p-! _ ~o r l.nc . -
1
counter== ox oshow(c- - - -- - -
For ssageB · ounter)
Me
Next
Figure 3.9: For... Next Loop
Initialization ·
Loop-qody
Next Statements
1
con sole app lica tion mo dul e in VB NET to pri nt num ber s from 1O to
. Now, writ ea ·
using F N
ent . Pro jec t 3.5 sho ws the sou rce cod e in VB.NET.
or ... ext statem
Using For... Next
Project 3.5: Printing 10 to 1 Numbers
ModuJ
e moct_foreach
S~b~ain() /
Using for ..each
Console W . • .
· nteLin e("P nnt mg 10 to 1 ")
p 1
Cmttro( Stl1Cebuea
Next
Console.ReadKey()
End Sub
End Module
The outpu t is as follows.
U file:///E:/vbprojects/Chapt~r_3_console/Chapter_3
·as follows.
Synta x ,
For each <element> in <group>
Loop-body ,J • I
Next
Example ~
. an array
'Array_num 1s J
For each arr_element in Array_num
Console. writeline(arr_element)
Next
Its usage is shown with Arrays in chapte r 8.
te m ent .
1E
xit D o /F o r S ta en d th e in n en n o st loo th at includes it
3, 3 . m ed ia te ly · ~~ te-ly fallowin Pth
E xi t D o /F o r st a te m e n ts imx t t t - ia
t im m ed op
g e cu rr en t lo ·
The '"' d t o th e n e s a em en
s1 er re . •h IF
d control is tr an . •
OlLW lL _a.£. --~ em en t.
an
It is us ed en er
all m co n
ent
_3 _2 Continue
D o /F o r S ta te m rr en
ki s a ll the
t it er at io n . an d s p
ly
o n_ _,J h
__ e
... cu
,,.. .... -
d s_ nning of
~
3 t~ n_
o n ti n u e D o
. /F o r st a te m e n _ ~ ~ ut io n st ar ts \\ jt h th e begi
---~r. . . . ___ __,___
The C o£._agd ex
w ri tt ~n m th e b ~dl_ o f~ ~lo er a ll y, w__it__h a n If st at
em en t.
., in st ru ct io ns al so u se d g en
h is k ey w o rd 1s . . . . @,,,.. ~
xt it_eration.~T
_ne
d
f D LAB EXERCISESa window application in VB.NET to rcacececopdet va. lue for N an
W ri te so u
Exercise 3 .4 .1 : b e rs . P ro je ct 3 .6 sh o w s th e
m
t N n a tu ra l n u
print sum o f firs tural Numbers
Project 3.6: Su
m of First N Na
Click
Public Class fnn_
sumN
s E ve nt A rg sJ Handles BtnGo.
ect, e A
S ub B tn G o_C li ck(sender A s Obj
Private
Dim sumN As In te g er
Dim i As Integer
i=1
alue. Text
Do While i <= txtV
sumN += i
i += 1
"
Loop ra l n u m b e; ~ is " & sumN)
tV al u e. T ex t & "n a tu
essageBox.Show("Sum o f" & tx
M
End Sub
· End Class
7
eommonl~ useb Controls of VB.NE1'
A variety of controls are pFovided in VB.NET which can be used for designing front
nd t
end of the applications .. These controls have properties and events. U erS anding of
these controls and events help in designing interactive applications.
I
<:!!
, -
--+ ·Categorized: For displa.ylng category wise properties
• .1 •·• ••,
- .•
9' --+ Alphabetical: For displaying ·.prpperties
'
in sorted order·
I
' > _. Property Pages: For displaying property ~ges- •.
Fonnl,vb* ~ X Forml.vb[Des,gnt
I!/ W,ndowsAppliation1 • f (Form1 Events)
l rcferenc: s
End Sub
End Class
given in Table 4 .1.
The commonly used prope rties and event s of Form contr ol are
I•
Property/
Descr iption
Event Name -
,,,,,.
Properti~
the
Name This prope rty is used in the sourc e code of VB.NET to identify
-8t Form e.g. frm cal, frm fact.
\
n.
artPosition By defau lt, a form appea rs in the upper -left come r of the scree
on
However, the positi on of the form can be chang ed. The comm
' , "
option s availa ble are:
- Common{;~ usw Controls of VB.NEl
MouseClick This event is used to write the code that will be executed when form
is clicked at run tirrie.
MouseDoubleClick event is used to write the code that will-be executed when form
This .__.. ~
I Me.BackC~lor _= Color.Green
Me.M~ miz eB ox = False
Me.Jdini.mizeBox = True
L
/
End Sub I
t -
_
/
nd Class _
The first line of code will £E_~gy th:
title of FoI_;!l to 'My Fir st VB.NET Pro
gra m', the
Color and the nex t line cha nge s
4 second line will cha
the background to
nge
Gre en
the
col
for
or.
egr
Sin
oun
ce
d
Ma
obj
xim
ect
ize
to
Bo
Red
x is set to Fal se, The For m can not be
•Jµ
' ,e_,,, ti , -l
' -
(f),:f7 t; •/--<. v·dI - ~1.-. _, N CJ
~
L. ., • I '
~ '-: t~ --
4.1.2 ~e l C on tr o~---
me ssa ge to the use r. Th is me ss~~
A Label con
-- ---- -- trol is wid e.If use d to
n
dis
abo
~
ut
y a
\the
-- -- -= =- =- -
rol e of oth er con tro l. It can be pla
ced on
be a generic me ssa ge or inf orm atio
tro l
of the Jol low ing two me tho ds. Do Ebl e_clic k cir clic k the Label con
the fonn usi ng one e
and the n pla ce it ' on the for m at the des ire d loc atio n. Th
4:!.__T..9_ol_Box window 4.2 .
of Label con tro l are giv en in Tab le
commonly used pro per ties and eve nts
Labele Control
Table 4.2: Properties and Events of
.../
l}mage
# the Label.
useMnemonic This pioperty is set to true, then the character preceded by &
symbol in Text property is interpreted as label's mnemonic key.
MouseUp This event occurs when mouse' -pointer is over label control and
~ mouse button is released.
-
' r
~MouseLeave ✓ This event occurs when mouse pointer leaves label control.
Now, design a Form having two Label controls on the Form. Display message
'Welcome to Controls' in one Label control. Write appropriate messages on Click,
MouseEnter, MouseLeave and DoubleClick events. Project 4.2 shows the source code.
Use the following steps.
► Draw Label c0ntrol on Form and set its Name property to lblMain
► Set Text property of lblMain to "Welcome to Controls"
► Draw second Label control on Form and set its Name property to lblMsg
' Write appropriate messages using events like Click, DoubleClick, MouseEnter,
MouseLeave.
cm,,monl~ meb COntrols of- VB.NET m
Pro ject 4.2: Using Label Control
pablic Class Fo rm l
nd er As Ob jec t, e As EventArgs) Handles
Private Sub lblMain_Cllck (se
JbJlfain,Click
lblMsg.Text = "Mouse is clicked"
End Sub rgsJ Handles
in_ Do ubl eC lick (se nde r As Ob jec t, e As EventA
Private Sub lbl Ma
JbJMain.DoubleClick
"
lblMsg.Text = "Mouse is double clicked
End Sub les
in_ Mo use En ter (se nde r As Object, e As EventArgsJ Hand
Private Sub lbl Ma
IblMain.MouseEnter
lblMsg.Text = "Mouse Entered"
End Sub les
in_ Mo use Lea ve( sen der As Object, e As EventArgs) Ha nd
Private Sub JblMa
lbJMain.MouseLeave
lblMsg. Text = "Mouse Left"
End Sub
End Class
r cho ice s are as follows.
The out put scr een s for different use
Form1
.
aO Form1
I
I
Welcome to C'.ortrols
I
I
4 3 TextBox Co ntr ol
·~· ..._
d gen era lly to get use r inp ut. It can als o be use d to dis pla y
ATextB.ox Control is i{se cti ce to- lceep
default, its narn~ is Te xtB ox l Tex tB~x2 an d s6o ri."1r is a good pra
text. By ' ----- etc.
names which are meani--ngful an d sel fex pla n~ toz y lik e txt Na me , qc~d_d.ress
~ - - -- -- ---
Double-er th app ear s m the up- pe r left
ick e Tex tBo x con tro l m Too 1Box. Th e TextBox · · - - -1
corn - Or clic k thi s con tro
~ of the - -
D ·
Form rag it to the des ire d pos itio n in the
· Fo rm .
once and th of
w it on the form. Th e com mo nly use d pro per tie s an d eve nts
TextBox en dra
control are given in Table 4.3.
,
m commonl:9 u.sw controls of VB~1
TextAlign
\ Alignment can be left, right or center.
ScrollBars This property is used to set the srcollbars for multiline text box.
"'
The options are None, Horizontal, Vertical and Both. ..
j) · kyi JJ -J µJ
ru-1
j
o
Public Class FrmTextBoxDe,
I
k
nd er As Ob jec t, e As Ev en tArgs) Handles txtMsg.Clic
Private Sub txtMsg_Clic.lqse
d"
Ib!Events.Text = "Textbox clicke
eave
End Sub
e(s en de r As Ob jec t, e As EventArgs) Ha nd les txtMsg.L
Private sub txtMsg_Leav
Events.Text = "Textbox lef t"
Ib!
txtEntered. Text = txtMsg. Text
rgs) Ha nd les
End Sub
ng ed (se nd er As Object, e As EventA
Private Sub txtMsg_Te xtC ha
txtMsg. TextChanged
g"
Ib!Events.Text = "Text ch an gin
txtEntered.Text = txtMsg.Text
End Sub
End Class
lows.
The ou tpu t scr een s are as fol
&ter1Ae$sage /I
J
~---_
&tered ~ is
p
IfY M0
d 100 = 0 Then
If y Mod 400.--=--0 Then
: -( -
~ ox.Sh ow('~The y~ar is a Leap year'')
Else
eBox Show("The year is NOT a Leap year'')
Messag ·
E d if ___ .--
,,.:;::::.:---»- - - -
Else
f Mod 4 = 0 Then '')
Iy . Le
Box Show("The year 1s a ap year
Mess age ·
Else
ox Show("The year is NOT a Leap year")
MessageB ·
End If
nd If
End Sub le■ bt:DExit.Click
tnExit Click (send er As Object, e As Even tArp ) Hand
Private Sub b -
Me.Close()
End Sub
End Class
~
The output screens are as follows.
alt
-
r &ter Yea- /2000 ,
The year is a Leap year
Ii ... L ei__] ~
l
OIC
-
i!:=== -:==:r ,;:z;:,r ,-;;c.z. a"""-" -=--=m =a:
I
~~ Co ntr ols of VB.NET
Proje ct 4.6: Calcu lating Simp le Intere st
Amount
Raia d ln18f9St r:- I
r - in Year /2 -/
~is2 80
flit
~ perty Description
o/
N tify Gro upB ox Con trol. For
This property is used in the sour ce cod~e to iden - - - -·-· - -· - --
r-- -_ example, grpChoice.
Te9 This property • on the top left
ed IS used to set/ get text (hea ding ) that app ears
~ ge of the GroupBox.
ForeColor
This property . in the
for chan ging the colo r of text disp laye d
~ GroupB F Is used
ox. or Exam 1
Pe, grpC olor l.Te xt-" Cho ose Fore grou nd Colo
r"
-BackColor
/ For Example, grpColor2.Text="Choose Background Color"
Qmmlmtl~ u.se.b COlttrols of VB.NEt
This property sets or gets background color of the GroupBox container.
Font The Font is used to set size, font, bold, italic etc. properties of the
1./ container displayed on Form. J
Property/ Method/
Snatllame
Description I
Pr.operties
Name This property is used in the code to identify the CheckBox control.
For example, chkSwimming, chkReading.
Text V This property is used to get or set the caption of a CheckBox.
Checked True or False value of this property indicates whether the
,: '-
CheckBox lS selected or deselected. For example,
chkSwimming. Checked=False
l,t;heckState This control can have three, states:-
► Checked (selected)
I
'
Checked Changed This event is raised on a change in the value of the Che~ked
• I
' property of the CheckBox cdntro~. -