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

chap 3 and 4

The document discusses various control structures in VB.NET, including nested If...Else statements, If...ElseIf ladders, and Select...Case structures for decision-making. It also covers looping structures such as Do...While, For...Next, and For...Each loops, explaining their syntax and usage. Additionally, it emphasizes the importance of readability and clarity in code, suggesting that nested Ifs should be avoided when possible.

Uploaded by

Arshdeep Kaur
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

chap 3 and 4

The document discusses various control structures in VB.NET, including nested If...Else statements, If...ElseIf ladders, and Select...Case structures for decision-making. It also covers looping structures such as Do...While, For...Next, and For...Each loops, explaining their syntax and usage. Additionally, it emphasizes the importance of readability and clarity in code, suggesting that nested Ifs should be avoided when possible.

Uploaded by

Arshdeep Kaur
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

The output is as follows.

[jJ file:///C:/Users/lndu Arora/App Data/Local


Enter :ne n~moen
30
a is not less :han 20

.1. 3 Nested if.... Else ... End If Select ion Structure


If series of decisions are involved in an application, then multiple "lf
-
--tJJ\...c...
.... Else"
-Else
tructur es are used in a nested way. It is always legal in VB.NET to nest If-Then
genera l
tructur es, which means an If statem ent can be used inside anothe r If. The
.
orm of a "nested lf. .Else" statem ent along with VB.NET snippe t is shown as follows
Syntax
If( boolean_expression_1~ I
-
If(boolean_expression_2)Then
-
<VB.NET Statements>

.End-If
Else
<Block for false evaluation of Boolean_expression_l>
End If
....,
, 11 I

Dim a As Integer = 100


Dim b As Integer = 200
If (a = 100) Then
If (b = 200) Then
MessageBox.show("Value of a is 100 & b is 200")
End If
End If
MessageBox.show (a)
MessageBox.show (b)
,~
The ~~es~e d If statemen!_.1!1.!X. -~1:!{(~!:.Jr<?m the problem of 'dangling else'
w_!lich if
nvolved do not have corresp onding 'else' part, then am_biguj ty may ari~ a~out
s associated with else. So, nested Ifs should be avoided .

. 1.4 If... Elself... End If Ladder Select ion Structure


It also involves series of multiple decisions like 'Nested If statem ent.
r
I

Con trol s~

Y and reada bility . Cond itio~


prefe rred by deve loper over 'Nest ed If for its bette r clari!
are evalu ated in serie s till a cond ition is foun d whfc n
cond ition s are not exec uted. If no such cond ition is
~ aluat es to true. The rest of th
foun d then_ 02yo nal_e lse block i:
in Figur e 3 .3. The gen~
. _exec uted . The flow of 'Nest ed If state ment is show n
snipp et is show n as follow s .
simp le "If. .. Elsei f... End If' state ment along with VB.N ET
Synt ax Code Snip pet
If cond ition Then Modu le modl f ' for conso le Appli cation
State ment block -1 Sub Main( )
Elsel f cond ition Then Dim Mark As Integ er
State ment block -2 Dim Grad e As Strin g
Elsel f cond ition Then Conso le.Wr iteLin e("En ter Mark s")
State ment block -3 Mark = Cons ole.re adLin e()
If Mark >= 80 Then
Grad e= "A"
Elsel f Mark >= 60 And Mark < 80 Then
(Else
Grad e = "B"
State ment block -n]
Elsel f Mark >= 40 And Mark < 60 Then
End If
Grad e = "C"
Else
Grad e= "D"
End If
Cons ole.W riteLi ne("G rade is " + Grade )
Conso le.rea dKey ()
End Sub
End Modu le

Figure 3.3: lf. .•Else... End If Ladde r Statem ent

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

Case 1 Case 2 Case 3 Case n ELSE

Statements Statements Statements Statements

Next-Statement

r t' write· a code in VB.NET which takes user mput


ap Now, . of marks using window
pica wn. Display the grade as per scheme given below.
Marks Grade
0-49 E
50-59 D
60-69 -C
70-84 8
85-100 A
Project 3.2 shows the source code in VB.NET .
.
I_
Control Stmctures

-
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"))

IIJ LOOPING OR ITERATION STRUCTURES


rol how man y time s a bloc k of code
Loops are powerful cont rol stru ctur es that cont
g a stat eme nt or grou p of stat eme nts
is to be exec uted . This way, it allows exec utin
con tain s the bloc k of stat eme nts to be
multiple times. The part of the loop that
-body. A one -tim e exe cuti on of a loop-
repe ated is called the body of the loop or loop
y is refe rred to as an itera tion of the loop . Eac h loop con tain s a con diti on which is a
bod of repe ating
of the bod y and the pro~
boolean eKPr essi on that cont rols the exec utio n
ition is met) The con ditio n of the loop
a sequ ence of inst ruct ions unti l a cert ain cond
ram can term inat e, othe rwis e it will
shou ld ultim atel y become false so that the prog
loop can be term inat ed usin g CTRL+C.
become an infinite loop. J:!owever, an infinite - -
- -
VB.NET provides following looping stru ctures.
(i) Do ...Whi le/U ntil .Loop J

(ii) For.... .Next Loop


(iii) For.. ...Eac h Loop
e in two ~ s, pre- test and pos t-test.
, The Do ..While /Un til in VB.NET are availabl
_sinc e it che cks cond ition first and ~
The pre- test is also called entr y,:controlled lo~p
call ed ..:_xit -<;cmtr~ll;d loop si~e }I]i]_t
take s actio n acco ram gly. The :P!?!'t -te~ is ~
exec utes loop ~ - and th,en .che ck&..._t he...._c,_ond -
ition :-
"

3.2. 1 The D~ ... Whil~ Loo p•' Gt~dJ,'~ Tm~ ~o ~ 0,-.t ~rl) J~ .

s w_he re the num ber of repe titio ns is


A Do ... While loop 1s. pref erab ly u ~ec_! ~n ~1: _~o form
offu ..
e. The gen eral and simples t
_not_.~ow n befor e star tmg the loop ing_ stru ctur
are given below. -
While m both the case s, pre- test and ,po st-te st
Pre-test Pos t-te st
Do While <condition> Do
VB.NET- stat eme nts VB.NET stat eme nts

--;;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

ft.!~ITowI. ., - 1.n Figure 3. 5 an


are sh n Loop (Pre-test)
Figure 3.5: Do...While

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~

Project 3.3: Printing 1 to 10 Numbers using Do .. While

\
Do...1"dle(Pre-te1t)
Do...Whlle(Po1t-te1t) --
~

Module Mod_dowhile_post
Module Mod_dowhile
Sub mainl) Sub main()
~

'using post-test do while


' 'using pre-test do while
Console. WriteLine("Printing 1 to 10
Console.WriteLine("Printing l_ to
in_post-test scenario")
10 in pre-test scenario")
Dim num As Integer / Dim num As Integer

mun=, 1' num = 1

-Bo While IllJID <= 10 · Do


Console.WriteLine(oum) Console. WriteLine(num)
num = num + 1 num = num + 1
,

Loop Loop While num <= 10


Console.ReadKey() Console. ReadKey()
End Sub End Sub
End Module End Module
The output screens of Do ... While pre-test and post-test are as follows. I
i3 file///E:/vbprojects/Chapter_3_console/Chapter_3_co liJ file:///E:/vbprojects/ChapterJ_console/Chapter_3_consol

-2', bo-:J.,.1 r ~-(',. tr,, 7.


3.2.2 The Do ... Unt il Loop J
A Do ... Until loop is also preferably used in scenarios where the number of
repetitions is not kno~ before starting the looping structure. The general ana simplest
form of Do ... Until in both the cases, pre-test and post-test are given below.
r-;;:::~~- - - - - - - - - , -_ _ ______::___ _ _ _ __
Pre-teat Post-test
Do Until <conq_ition> Do
VB.NET statements · VB.NET statements
Loop Loop Until <condition>
aua- EJD
e,ontrol structures .
rm in at ed an y tim e with th e lE J.;,_
'iiP
xit
___ ...J_ st.ateme nt. Th e ma.in
Until co ul d be te es t
U .1 m • pr e- te st an d po st -t
The D0 -... us e of Do.. nt1 Joop -bsocdenan o isdin th at Pre-test
ex ec ut es th e
on fi rs t an d th en Y de pen g upon the
difference thine co nd iti · ut es th e lo op -b od y fi
rrst an d th. ~ eval uates
_ 1 at es
h co nd iti on . While po. st -t es t ex ec . lt of th
evwU
lt of t e is
-
co nt m ue d de pe nd m g up on re su e ro n d1 t-io n. In both
resU d J't'10 n . Th e lo op
ua te s to false, th e bo dy of
th e 100P -.is executed Jf
con •
nd iti on ev al the
the s if th e co --~ ... ..- -- -.- --
nn in
-:
at es an d th e orogram control
1 - - .t.ire .Jo op te_ -
;ies-to...tr:ue,.....e.ceD moves
-
· · o ... U nt
.
il lo op . Th e flow of D .. UntJ.J (pre -test)
d1twn e at em en t th at ,iollows th e D o.
con xt st -- - h · • 7 an d Fi gu re 3. 8 re sp e cti ve1.y.
the ne nfl'f(post:.-- test) ar es ow n m Fi
gu re 3.
to _Do ----V
/4l'fd ... Until Loop (Pre-test)
Figure 3.7: Do...

In iti al iz at io n

Tr ue
· False
(End of loop)
Until loop bo dy

ts
,.___--Next St at em en

Figure 3.8: Do ... Un


til Loop (Post-t~st)

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

..; i>o..Until(Pre-test) Do..Until(Post-test)

Module Mod_dountilPre Module mod_dountilpost

Sub main() Sub main()


'using pre-test do until 'using post-test do until
Console.WriteLine(" 1 to 10 in Console.WriteLine(" 1 to 10 m
do.. Until pre-test scenario") do .. Until post-test scenario")
Dim mun As Integer Dim num As Integer
mun= 1 num = 1
Do Until num > 10 Do
Console. WriteLine(num) Console.WriteLine(num)
num = num + 1 num = num + 1
Loop Loop Until num > 10 .... ~

Console.Read Key() Conscle. R~adKey()


End Sub End Sub
End Module End Module
The output of Do ... Until (pre-test) is The output of Do ... Until (post-test) is as
as follows. follows.
f: file:///E:/vbprojects/ChapterJ_console/ChapterJ_con ~-,
1 file:/// E:/vbprojects/Chapter_3_console/Chapter_3_console;
dc . . Un:~1 ore-t~st scenario 1 :o 18 in do . . Until post-tes: s:2na r!a
1
2
3
4
)

6
7
0
u
G

10

3.2.3 For ... Next Loop

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 ·

False Increment/ Decrement


(End of loop)
Statement

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

Dim num As. Integer


For num .= 10 J'o 1 Step -

Next
Console.ReadKey()
End Sub
End Module
The outpu t is as follows.

U file:///E:/vbprojects/Chapt~r_3_console/Chapter_3

3.2.4 For... Each Loop


The For... Each loop is used ~ hen the body of the L~of:> ~~e _execute_d
for~
1t_b~~ ~s
eleme nt in_collection. rThe C?O.ll~ctiop Cc\£ ,be.. ~ -~aY:.~.!!~ ~···Ea ch l~~p_,
e asy to assess and manip ulate eleme nts of collect
, ______ _ _ . _ -r •
ion.~The syntax along with examp le is
•. - - - c:

·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.

3 .2.5 Nested Loops


be completely
, A loop with in a loop is allowed in VB.NET. The inner loop shoul d
within the outer loop. There should be no overla pping of loops.
control structures
Bil
S
STATEMENT
flJ B R A N C H IN G
s a re ex ec u te d g en er a ll y fo r
a fixed
n u m b er o f t...,.a
;-
1es dep en1.U
,i; _
I1g
o f th e lo o p . o m es n ee sk i
dy l d . W h en ev er , 1t b ec
.f1e es sa ry to P a P ar t of th
Bo e co n d it io n spec1 . . f th e
th . e n ts h el p m Ju m p in g o u t o e bo dy o f th loop . These
upon loop, p ra n ch 1u g st a te m -
e
O
f
-
bodY ar e "'·
st at em en ts
r S ta te m e n t
(i) Exit D o /F o
nt
e D o /F o r S ta te m e N
(~i) C o n ti n u
t~ m ep ts ar e ~ se d within F o r ext loop. While
~a ···
cLC , o n ti n u t; Eo r.. ithin do loops.
The Exi t For an s ta t~JI1ent s_ a re .u se cL w
~ c:lsCQnti11ue,..do_

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.

DI COMMONLY USED CONTROLS


VB.NET pr_Qyides ~ de range of controls lik~abel, TextBox, Button, RadioBu~
CheckBox, ~ etc.·Every c·ontrol has .E_roperties and events ~ i t . When
a particular control is selected, its associated properties ,are di~ ~op~
window of Visual Studio I{?E_. The property windowj!§1§._aU the objects of an_ active
form which can be seen ""izy1Ifckin~ o.n..the_dt.9.P down arrow of thµ-st-.. .-!!_ ~so co.
icons to categorize, sort and. display properties and events. Figure 4.1 shows the ic~
available in property window.
Figure 4.1: Icons of Property Window

I
<:!!
, -
--+ ·Categorized: For displa.ylng category wise properties
• .1 •·• ••,

- .•
9' --+ Alphabetical: For displaying ·.prpperties
'
in sorted order·

-~ · --+ Properties: For displaying properties of selected control

,.·I --+ Events: For displaying. events of selected control

I
' > _. Property Pages: For displaying property ~ges- •.

The subsequent sections cover the following controls wh· h


designing front end of application in VB.NET. ,c are® nly used in

' Form ► Ra~lt~ ~~~~ l


~
.

, Label l
Picture8~~0 ,'l .
► L1stBox ~p" \ ~
, TextBox
I
► Button ► ComboBox
I ,.. GroupBox ► DateTimePicker
, CheckBox ► Pr~gressBar and Shape controls

4 .1.1. 1'._orm Control /


~
~ob C),
~v\.O.Jt.,

~ Form can be developed usin s .


available jn System Nam•es th' g ~stem.Wmdow s.Forms.Fog:n_ clas.s. which is
- - ~ ~a~ e main n · -
Framework. The Form control co t . ames2; ce m the class library _of .NET
---- - -_set at the design time and/ n ams proI?erti h
can be or run . es, m et ~da.and_events..-The properties
~ e. If properties of the Form Control are to
____ _ _ __,,.!:__::::.::::..:_:~~~ ~ :_t~im
o,mmOJtl;!J usea Qmtrols of VB.NET Ill
the FOTJ'!!._i.e . at Load
~ • it_is better if the~ are s~ at the loadin g of
are a ctivat ed. click.
~ t . The other m81fl event s assoe tated with the Form class
ofthe
~ etc. Their detail ed list can b~ seen on clicki ng the uppe r righ tpane
in Figur e 4 .2 .
code window. The defau lt event of Form ! ts Form l_Load as given
Figure 4.2: Displaying Form1 _Load Event

Fonnl,vb* ~ X Forml.vb[Des,gnt
I!/ W,ndowsAppliation1 • f (Form1 Events)
l rcferenc: s

sectio n for _gefau l t


If developer doubl e clicks on the empty area of Form , then code
this event hand ler is
event (Load) is opene d in the code windo w of Form . The code for
des the
;;iite'ii ~thin Priva te .S ub ....End Sub. Its defau lt name ('Forml_Load) inclu
It is furth er followed
name of form, followed by under score symb ol and ~ d keyw ord.
by paren theses that inclu de two param eters ~ r' and 'e' which are objec ts of class
paren these s, it uses
System.Object and Syste m.Ev entAr gs respec tively . After
is comm only used to
keyword 'hand les' followed by MyBa se.Lo ad~y Base ke~o rd
a derive d class . Withi n
access base £~~ 1!1~1!!b er~ ~ ~ _?,verr idden or shaq o~ eq_in
'F~rml Load' event hand ler devel o er can write code to_ch
ange Form 's appea rance
an or perfor m initia lizatio n tasks . The code looks like
as follows .
. ·NI'
Public Class Form l '('/Jfl'/'J- ef~ ~ ~ tt~J
,Erivate Sub Form1_J..oad(fu'V.. al ~nde r.;.;.;
;;;..,-'·
As,Sy stem. ObjecS, ByVal ~ ;As_
~
'
,J)ii"~.,.~yste m.Ev entAr ~j Hand les MyBa se.Loa d -
M,t/(

End Sub
End Class
given in Table 4 .1.
The commonly used prope rties and event s of Form contr ol are

Table 4.1: Properties and Events of Form Control

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

(a) Manual: The form is displayed accor~ing to coordinates (X,Y)


set in the property, Location. At run tipie, the form appears at
X and Y coordinates.
(b) CeneterScreen: This option sets the form at centre
(c) WindowDefaultLocation: This is the default setting.
Other options can be taken from the drop _down list.
l---------1-==~==~=-=~ -------------=-----
This prop_Ja:ty of a Form is set to the Name property of a Button,
AcceptButton
then corresponding button becomes a default button, ~
key is pressed. ---~-----
L _ _ _ ___J___::::~=:::::::::::::=-------
CancelButton This ~ .ei:ty of a Form is also set to the Name property of a
Button, then corresponding button becomes a Cancel button-~
~ cap~lipr is eressecL,
WindowState This ~operty can be set to normal, minim~ed or maximiz~ te.
The selection determines the initial visual- state
!
of. the
,..
Form.
.

IsMdiContainer ·This pr.QP~rty is set to true for creating a Form as Multiple


Document Interfa<::~ (MDI) Form.
~ oreColor This p!:Q_P.erty is set to change the color of text of the components
..,,
on Form.
font The Font pr~rtY is used to set size, font, bold, , italic etc.
properties of the components displayed on Form. - I

This property is u ~~d to display the text on title.of the Form.


MinimizeBox If this property . . a.
.---....... is set to False, Form cannot be minimized.
.
MaximizeBox If this property 4s set to Fals~, a _Form cannot be maximized.
However, ifboth MinimizeBox' ~d MaximizeBo~ set to False,
they are not shown in Form window at run time.
Event Handle~
'
Lbad This event is used to write the code 1that will be executed when fonn
,../
is loacted at run time. / · • · -:----.

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 .__.. ~

is double clicked at run time. ·


MouseDown This ewa-t occurs when mouse p_o.int~r is~ rm co~ti:ol.
r ~Q__
MouseUp This event occurs when mouse ,pointer is over Form control and
m ouse button is released.
MouseLeave This ~ t occurs when_mouse pointer leaves Form control.
,e,ommonl~ uMW Controls of ~.N ET m
ox and
Text, ForeColor, BackColor, MaximizeB
Now, write code i~ VB.N~T to c~a nge rce code .
1
pro per ties du nn g loa dm g of the Form. Project 4 . 1 shows the sou
MinimizeBox
Project 4.1: Form_Load Event

public Class Fo rm l e.Load


ate Sub Fo~ l_L oad (se nde r As Ob ject, e As EventArgs) Handles MyBas
Priv
g the ins tan ce of curren t Form.
, The keyword 'Me' is use d for referrin
-.
Me.Text= "My First VB .NE T Program"-
- ..-Me.ForeColor = Color.Red

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

maximized . The out put is as follows.

•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

Property/ ~ De1criptfo11 ._-.:


Events Name
~ f?pertles -
code to identify the Label
\.-
,...Name
This pro per ty is use d in the sou rce
Control e.g. lbl_nam e, lbl_add r.
ForeColor ~ color of tex t of Label.
This property is use d to cha nge the
m -
Common{~ ~ Controls of VB~

✓' This property sets background color of the Label control.


v "BackColor
~
This property is used to set size, font, bold, italic and many
Font
~
:
more properties of the Label.
/ This property is used to set or display message on the Form.
-
-ext / This property is set to False, if Label control is to be made
Visible
/ invisible. By default, it is True.
,.
• I
Border$tyle
This property can be set to none_. FixedSingle or F~ ed3D. By

~ default, Labels are set to none.


This property includes path to image that will be displayed
., 0~

.../
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.

£-!ent Handlers .. / 1A!J. ~ ~


MouseClick/ Click
~ , . . - --
These events are used to write the code that will be executed
when label is dicked at ruh time. The MouseClick event is not
-
raised if the click is causecl by ~ y other action which is not
related to mouse. But click event can be raised on pressing
r
Enter key.
MouseDoubleClick/ These events are used to write the code that will be.J:)Cecuted
DoubleClick ✓ when label is double clicked at run time. Th e difference
between MouseDoubleClick and DoubleClick is same as given
f

in MouseClick / Click events. I

mouse pointer is over label control. I


.MouseDown V This event occurs when
- ~

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

Mouse Entered Message is cidc«1


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

Table 4.3: Properties and Events of TextBox Control

Property/ Event/ Description


Method Name
L~~~~~-L ______ ______ ______ ___
Properties
This property is used in the source code to identify the TextB;
.,,-Name /
control e.g. txtName, txtAddress.
:-
L--- ----j_~~ ~~ ~===-~~:__--:--:-:---:~~=~~~=~:---
This property is used for changing the_color of text displayed in the
Foretolor __A
✓L-----~-~T,:ext~B;;o~x~.------- ---:-~-:- -===-;-~=: -:;-:-l
BackColor V This property is used for changing the_ background ~olor of the
TextBox control.
This_ property changes size, font, bold, italic and many more
Font
properties of the TextBox.

Text This property includes the tex!_/ ~ e~s~ ~ ?i_s:r~~Y:~d on screen.

,Yisible ./ Th~s property is set to false to make a TextBox invisible.


"
-~rcferStyle / This property is used to change BorderStyle of control to none,
\,

FixedSingle or Fixed3D. By default, Textboxes are set tcYFixed3D.


This property is set to True for making TextBox as a multiline
Maltiline / TextBox control.
This property is used to change the alignment of TextBox.
/
\

TextAlign
\ Alignment can be left, right or center.

WordWrap This property is used to control the wrapping. of w.9rds in a


✓ multiline TextBox control. ,,,,. .-'\,t, w iJJ- 'r·-A-
~ \) (\
)r,,.l}-1,2.... ·_; ., v.J-: c""' \ -'j>'Y'Q.,,
(1 , .. • \ \ '" o__

SelectedText This property is used to change the valu~ of curre'~t1y' selea€ruxt


from the control box. l...vi- ~

SelectionLength This property is used to change the value of numb~~ of charact~rs


✓ selected. , ,i •

ScrollBars This property is used to set the srcollbars for multiline text box.
"'
The options are None, Horizontal, Vertical and Both. ..

PasswordCha v This property is used to set a character for display in place of


actual character entered.
~
. I~ " .-t
l .._,.
-~ ~, , _,.
- N,.J "'i]t) ll'o1 A,
t

TextChanged _,,,, / / ~ default event procedure is l ~xtChanged which is invoked on


changing the text. .' .,.I -'- r •

Mouse related / MouseClick/Cli ck, MouseLeave, MouseDown, MouseUp,


th
events MouseDoubleCl ick/DoubleClick , work in the similar way wi
TextBox as they work with Label control.
c;onononly useo Omtrols of VB.NET m
Me tho ds I
Th is me tho d is us ed to cle ar
the tex t in the textbox. i
()
· Fo r ex am ple , tx tN ~e :Clear
· tm
us or .ins ert ion p om · th e TextBox
Th is me tho d is us ed to set foc ·
s()
Fo r ex am ple , txtName.Focu
xtB
nte nts of selected tex t in Te ox to
Th is medtho d co pie s the co .
Copy() . b
c11p oa r .
ox fro m
nte nts of sel ect ed tex t in TextB
Th is me tho d rep lac es the co
Paste() cli pb oar d. ,
ols
ET tha t us es tw o La bel co ntr ols an d TextBox co ntr
.N
Let 's no w wr ite co de in VB on e La be l co ntr ol an d "En ter ed Me
ssage
nte r Me ssa ge " in
the Fo nn an d dis pla ys "E e Te xtb ox sh ou ld als o ap pe ar
in sec on d
ssa ge typ ed in on
??, in oth er Label. Th e me e co de .
x usi ng dif fer en t ev en ts. Pro jec t 4 .3 sh ow s the so urc
;extBo
, , , ,.· • ·
Project 4.3: Usin~ ;ext~ox
,,_:_i

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

gg eommonl;!) useb Controls of VB.Nrr

4 . 1.4 Button Control


Button Control is used to perlorm actions by invoking eve~ han~rs. Dm~ble click the
·
Button control fro'II}. . appears m
ToolBox and 1t • the upp•e r -left
-- comer of the Form.
-. Drag it to
• • • :.. - - • tr
the requrred pos1ttort m the Form. Or click the con o on J ce 'and then
. draw
. 1t on the Fonn .
The commonly used properties and events- of Butt on ·c n:trol are 01ven m Table 4. 4 .
° t:,6

Table 4.4: Properties and Events of Button Control

Property/ Event Description - '


.Name
Properties
-
Name This property is used i n the source code ~o id~ntify the Button
Control e.g. btnExit
- -
ForeColor ./ This property is used for changing/
..,. getting the color of text
displayed in the Button control.
BackColor This property is used for changing/ getting background color of
the Button control.
Font The property is used to set size, font, bold, it~c ·e tc. properties of
- the Button displayed on Form.
Text This property is used to set/get the text to be dis~yed on I
BUtton control. , ·
Image An ,nnage on -a button contFOl will be dis_p layed ~ t t i ng the
' Button's Image property to a valid picture. I

Visible This property is set to false to m~e a Button invisible. . I


l
'Event :Handlers j
-· -
Click This default event of Button is used to write the code that will be
executed when Button is clicked at run time.
,,
There ar,e other events like MouseLeave, MouseClick, MouseDown, MouseUp etc. These 1

events are used in similar manner as described in Label control section.


-
Note: After adding a control to Form, set the properties of the control at design time
or change them at run time with the help of code.
Now, let's write code to accept year from the user in a TextBox, check whether it is
leap year and display relevant messages. Project 4.4 shows the source code.

Project 4.4: Using Button Control

PubUc Cius btnDemo


Private Sub btnShow....:Click(sender As Object, e As EventArgs) uandle5
btnSbow.CUck
Dim y As Integer
y = txtYear.Text
~~ u.se3 controls of VB.NET

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:

Now, write code that accepts heig ht and weig ht of a


pers on and calc ulate s Body
Mass 1ndex (BMI) of a person and disp lays appr opri ate
mess ages . Project 4.5 shows the
source cod . VB ·NET. The formula to calc ulate BMI is Wei ght/ (height*height) where
. . . em . . .
Weight IS m ki1 as follows.
ogram and height 1s m mete rs. The BMI cate gori es are
BMI Cate gory
<18.S Unde rwei ght
18.5-24.9 Normal
25-29 .9 Overweight
- ~30
Obes ity

I
~~ Co ntr ols of VB.NET
Proje ct 4.6: Calcu lating Simp le Intere st

Class fnDSI EventArga) Han dles


public b btnCalculate_Clic.k(•ender Aa Object, e Aa
,rwate Su
Calculate.Click
btn s· l
TE TIME, Inte rest As mg e
DiJil PA, RA '
..-Arnount.Text
PA .. l.JI.~ ·· -
,RATE== txtRate.Text
TIME ~ txtT-HDe. Text
.. (PA* RAT E* TIM E)/ 100
Interest
T xt .. "Interest is " & Inte rest
Jbllnterest. e
Jnd sub Han dle• btnE zit.C llck
btn.Exit Clic k(se nde r Aa Obj ect, e Aa EventArgs)
Priffte Sub -
Me.Close()
JndSub
Jnd Clall
The output is as follows.

Amount
Raia d ln18f9St r:- I
r - in Year /2 -/

~is2 80
flit

4.1.5 GroupBox Container


GroupBox control is used as §..._.C onta iner fQr.,,
..Qth.e_r con.tr:ols.._e. spe ci~ for radio
use d p ropertie s of Gro upB ox are give n
button_and check box cor{trols. The co~ ~onli
1ii'fa.bie4.5.

Table 4.5: Properties of GroupBox Control

~ 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

4 .1.6 CheckBox Control


A CheckB.ox control allows the user to select multiple options at a time. For
example, a user having multiple-hobbies can select or deselect multiple c~eck boxes by
clicking on them. WheJ J ~ox is selected, its Qle.cked---pt=epe-Fty 15 set to true;
otherwise it is set to
,. -
handlers of CheckBox Co
e commonly used properties, methods and event
given in Table 4.6 A.
Table 4.6 A: Properties and Events of CheckBox Control

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
'

► Unchecked (not selected)


► Indeterminate (graying ' out), this is applicable if
I ThreeState property of this control is set to true.
~reeState This property is set to true for allowing this control to have three
,- states-checkeq, unchecked and indeterminate rather than 1two.
.. -
~
;'
ppearance This property is used to change the appearance of the CheckBox
control. _,...

CheckAlign This property is used to change the horizontal and vertical


alignment of ~ e check mark on the check box.
~ Events '

Checked Changed This event is raised on a change in the value of the Che~ked
• I
' property of the CheckBox cdntro~. -

You might also like