Chap 6 and Cha8
Chap 6 and Cha8
e afte r add in d
iJlStance of Date object. For e! npe, --
alys passed to mJ
it with an
add Day s(20 ) retu rns 22- l0-2 0lS 13: 02 43
:
Ret urn s -~
date tirn e afte
i n ~ -'': -:°1'j ect.r For
add ing ho
examp::.• passed to it with an
addfiours(2) retu rns 02-10-2018 1s:02 43
,
s
Ret urn s dat etir ne afte r add ing min ute pas sed to 1·1 ·th
ins tan ce of oat e object. For example,
WI an
addlllinutes( 1OJ retu rn• 02-10-2018 13: 12 3
:4
.
Ret urn s datetiJJle afte F
r addillg months passed t o 1t
. with
. an
inst allc e o Date obiect. or example,
f
addlll nths(2) retu rns 02- 12-2018 13:0
2:43 \
0
Ret urn s dat etir ne ~te r aFdding seco nds
pas sed to it with an
iJlstance of oat e obJect. or ,xaIDple,
._ddseconds(I0) retuJllS 02- 10-2018 13:0
2:53
Ret urn s dat etim e afte r addillg years
passed to it with an
iJlstance of oat e object. For example,
.,,aiue as 1J1teger) addyears(2) retu rns 02- 10-202 0 13:02:43
addyears (
com par es dat e val ue pas sed to it with
the instance of date
(callitlg object) and retu rns an inte
ger <O, •O or ,o
dependitlg upo n wb etb er tbe value pas
CottlPa.re'fo(dateObj 1 as sed with the calling
object is ear lier tha !l, equ al to or greater
tha n <dateoObj 1,.
oate~
for e,carnple,
DiIIl obj 1as oat eTi rne
Qbj 1:::" 22-12-2018"
cur rDa te. comPareTo (Obj I) retu rns value <O
com par es dat e val ues pas sed to it.
This (u!lction return•
an jnteger <0, •0 or >0 dep end ing upa
n whether dateObj
is ear lier tba !l, equ al to or gre ate
Coropare(dateObj as r tba!l dateObjl. For
DateTirne, DateObj 1 as
DateTirne) / exa mp le,
Dim Obj 1as oat eTi rne
Obj 1=="22- 12- 2018"
Date. com par e(c urrpat e ,0bj I) retu
. rns
• h-1th<0 instance of date
Compares dat e val ue pas sed to 1t Wlt ue to Uldicate
eal . .
\Equals(dateObj as (calling obj ect) . It ret urn s a aoo lea
!l
DateTime) J wh eth er dat es are equ al or not - for exan v
>Ple,
Dim Obj las DateTirne
Obj 1=="22- 12-201 8"
cur rDate.Equals(Obj 1) ret urn s Fal se
-
~:-:-:------,_ _ _ _ _ _
qua ls(d ate Ob j 1 as
DateTime, DateOb2 as
_ _ _ i
·
4
°
j,
Compares date values pas sed to
value to indicate whether dat es
Built~ni b..
Me. Close()
JJld sub
todCJa8'
~ =-·
The output is as follows.
I Methods of Date · - D X
18
current date and time is 02-10-2018 14:01:
kJdHcxn /s
_ _I
lddYen /2 I
kJd Mnies
ldd ~ /-3 I /25
ldd Day /23 I kJd Seconds /29 _ ___JI
Updated Date is 25-07-2020 19:26:47
Updated date is Latest
l Exit
6.2.s Form .
atting Functions
..._____
Forrnatti
ng functions are used to convert a value to a formatted value. The Format()
r
BuilHnPJt
en
fer ent for ms de pe nd ing up on the format giv ' ·
fun cti.on ret urn s the
va lue s in dif · l'her,
of Fo rm at fun cti on s.
are two typ es
Bu ilt- in Fo rm at Fu nc tio ns
ns
Us er de fin ed Fo rm at Fu nc tio
Description
Sty le Value
ing separators. For example,
General Displays the nu mb er without hav
Number") ret urn s 56 73 64.2384
Number Format(567364 .2384, "General
it up to two
having sep ara tor s an d rou nd s
Fixed Displays the nu mb er without
decimal places. For example,
ret urn s 567364 .24
Format(567364.2384, "Fixed")
two decimal
arators an d rou nd s it up to
Standard Displays the nu mb er with sep
places . For example,
") ret urn s 5,67,364 .24
Format(567364 .2384, "Standard
I
arators a~
Currency sign in front, ha s sep
Currency Displays the nu mb er with the
imal places . For example,
well as rounding it up to two dec
y") ret urn s 5,6 7,3 64 .24
Format(567364.2384, "Currenc
% sign and
Percent rts the nu mb er to the per centage form an d dis plays a
Co nve
ces . For example,
rou nd s it up to two decimal pla
s 23 .84%
Format(0.2384, "Percent") ret urn
eral format. For example,
General Date Displays date an d time in gen
Dim cu rr_date As DateTime =
Now()
51
te") ret urn s 02 -10 -20 18 18:44:
Format(curr_date, "General Da
r example,
Long Date Displays date in long format. Fo
Dim curr_date As DateTime =
Now()
) ret urn s 02 October 20 18
Format(curr_date, "Long Date"
For exa mp le,
Short Date Displays date in sho rt format.
Dim cu rr_dat e As DateTime =
Now()
) ret urn s 02 -10 -20 18
Fo rm at( cur r_d ate, "Short Date"
11111
. ns
·(t in Funct10
BUI - - -i-::- :--: ---: -:-~ :--- ---- ---- ---- --- - 7
.
r,ong rune Displays time in long time. For example,
Dim curr_da te As DateTime = Now()
Format (curr_d ate, "Long Time") returns
18 :44 :Sl
snort 'fime Displays time in short time. For example , 18:44
write code in VB.NET to demon strate the wo kin f fun .
..t ..,
. • T ble
,iect 6.6 shows t h e source code.
1,0.. r go ctions given m a
6.6. PrOJ
Project 6.6: Using Date Format Fu ct·
n ions
Class frmDataFormat
pubUC
prlvate Sub btnGo_ Click(s ender As Object, e As EventArgs) Handles btnGo.Click
Dim ret_string As String
Dim curr_date As DateTime = Now()
t string= "Forma tted results are:-" & vbNewLine
re_
t string = ret_stri ng &
re - Number") & bN L'"General Numbe r Format is " & Format (-Val T
ue. ext,-
•Gener al v ew me U\.l
ret_string = ret_stri ng & "Fixed Format is " & Format(bctValue.Text, "Fixed") &_
vbNewLine
ret_string = ret_stri ng & "Standa rd Format is " & Format(bctValue.Text, "Standa rd")_
& vbNewLine
ret_string = ret_stri ng & "Curren cy Format is" & Format(bctValue.Text, "Currency")_
& vbNewLine
ret_string = ret_stri ng & "Percen t Format is " & Format(txtPer.Text, "Percent") &_
vbNewLine
ret_string = ret_stri ng & "Genera l Date Format is" & Format (curr_date, "General_
Date") & vbNewLine /
ret_string = ret_stri ng & "Long Date Format is " & Format(curr_date, "Long Date")&_
vbNewLine
ret_string = ret_stri ng & "Short Date Format is" & Format (curr_d ate, "Short Date")_
&vbNewLine
ret_string = ret_stri ng & "Long Time Format is " & Format (curr_d ate, "Long Time") &_
vbNewLine
ret_string = ret_stri ng & "Short Time Format is " & Format (curr_d ate, "Short Time")_
&vbNewLine
lb!Show.Text = ret_stri ng
End Sub
Private Sub btnExi t_Click (sender As Object , e As EventArgs) Handles btnExit.Click
Me.Close()
End Sub
End Class
b
,..ll,
Built-ht 1:..
~
- - -- -
Specifier Description
I
....
,~
~ ~- - - ~ ____
---:~-
h
24) i n 2 4 0 <>nnat
O1 a n d
p¢/t4
',,,,,~
1 the hou
r(
e m in u t e
between
s ( b e tw een 1 a
n d 59)
59)
tw e e n 01 a n d
e s (b e
e m in u t d 59)
( b e tw e en 1 a n
ds
e secon n d 59)
( b e tw e en O1 a
s
e second arators
it h o u t sep
v a lu e w arators
n u m e r ic i n t w it h o u t sep
im a l p o
e to 1 dec parators
n u m e r ic
v a lu
o i n t w it h o u t se
e c im a l p
ic v a lu e to 2 d
numer
re v a lu e
ig n befo
e
arentag
a]ue to p ed
o w in g customiz
rator fo ll
, as a sepa c u r r e n t date in
, e
p la y t h
VB.NE T t o d is
formats.
-YY
dd-MMMM
dd-MMM
MMM-yyYY , ET.
-d d e c o d e in VB.N
M c
yyry-M the s o u r -
t Specifie
rs
t 6. 7 sh ows
: Using Forma
P rojec ct 6
Proje
. 7
le s
tArg s } Hand
e A s Even
s frmCu
stomized As Ob je c t ,
Publlc Clas _Cliclc(sender
o w
b bttJSb
Private Su
Uck
btzJSllow.C Time =N
ow() Line
ate As Da te
- y y ') & vbNew
Dim curr_d d-MMM
M
ewLine
in g As S tring t ( c u r r _ date, "d M " ) & vbN
re t_s tr o r m a - M M
Dim :" & F ate, "dd & vbNew
Line
d-M M M M-yy o r m a t (curr_d - y y y y ')
ret_string=
"d :" & F "MMM
& "d d-MMM c u rr date 1
ret_str in g orm a t ( ') & _
ret_Strfug = - y y y y :" & F - , '' y y y y -MM-dd
t_string &
"MM M rr_date
Strfu g = r e " : " & F o rmat(cu
ret_ -dd
r e t stri g & YJYY-MM
ret_stnng "" - n
vbNewLine
string)
MessageB ox.Show(ret_
"
~u1d Bub
E11d Claq
r Built-in ll. .
....1t11cr
The output is as follows .
0 1( J
6 .2 .6 String Functions
/\ string r-e--pFe-S@n.1:-S-a-Series of characters _where each character represents
instance of the Char data type. The Sy~tem.String class help&_ in creating ;n,,..... an
. . -- ~~u.uUtabJ
strings i.e. co~ ant or fixed length_ stnngs. Such strings cannot be changed t__ e
same memoryl oca tion- - their
after - creation.
- A new string is created whenever sfrina ~
. .
processed i.e. a new stnng 1s ob taine
. d . d
an stored 1n
.
some oth er String objectgsaftare
applying methods. The syntax to create a string and assign value is as follows. er
Dim MyS~g As Stri.(lg
- •
MyString. ~ Amav
11 11
A s!Jing is immutable which implies its value cannot be changed once it has been
created. I.e. immutable strings cannot be modified. When such string is modified, a
new string object is created with modified value. However, an immutable string can be
assigned another value.
MyString = "Lipakshi"
MyString variable is reassigned a value. This string variable dis.cards its reference
to the first instance and stores a reference to the new instance. String is a reference
type, which means when a string is passed as an argument to a procedure, a reference
to the memory address is passed instead of the actual value of the string. ~
A string literal may comprise of one or more characters enclosed in double quotes.
A quotation mark within a string literal is represente d by two consecutiv e quotation
marks, otherwise a compiler error occurs.
I
·
Strings can be concatenat ed using the symbols ,e/,
sign and '+'. If one of tbe
vanables 1s· o f numenc · data type , '+' sign cannot be ·
used as data type m1sma tch error
occurs. Instead of '+', the symbol'&' is used for concatena ting different types. .
. . . hich is
The default value of a Stnng 1s null. It is different from an empty stnng w d
1111
represente d by String class provides number of functions to process all
•
VisualBasj c.gf! The Left() function takes out n characters starting from
Microsoft. - ~
('String", n) 7 the left of a String. For example,
Microsoft.VisualBasic.Left(strVal, 5) returns "VB.NE".
Replace( str as String, The replace() function is used for replacing part of text in
searchtext as String, a string with some other text. For example,
replacetext as String) Replace(strVal, "VB", "Visual Basic") returns "Visual
Basic.NET Programming.
Reverse(str as String) The strReverse() function reverses the string. For example,
StrReverse("ARNAV") returns "VANRA"
String.Compare( strl as The String.Compare method is used to compare two
String, str2 as String) strings. It returns an integer that indicates their relative
\ position in the sorting order. It returns 1, if the ASCD
value of the first string is higher; it returns - 1 if the ASCD
value of the second string is higher and returns O if both
String.Compare( strl as
strings have the same value. To ignore case, specify True
String, str2 as String,
as third argument; otherwise specify False. For example,
caseStyle as Boolean)
Dim str 1 As String
Strl = "Amav"
Dim str2 As String
Str2= "ARNAV"
Dim result As Integer
result= String.Compare(strl, str2)
result= String.Compare(strl, str2, True)
Built-ht b..
4'11' 4
Asc(code as Char) The Ase() function returns ASG.JI. code for a character Ot
symbol. For example,
Asc("A") returns 65.
Ase("%") returns 37.
Replace( str as String, The replace() function is used for repl,acing part of text in
searchtext as String, a string with some other text. For example,
replacetext as String) Replace(strVal, "VB", "Visual Basic") returns "Visual
Basic.NET Programming.
Reverse(str as String) The strReverse() function reverses the string. For example,
StrReverse("ARNAV") returns "VANRA"
Display in MessageBox I
Button Constant Name
OK but ton . I
~ OK
, OK and Cancel but ton s.
OKCancel
Abort, Retry and Ignore buttons.
AbortRetryignore
Yes, No, and Cancel buttons.
J YesNoCancel
' YesNo Yes and No but ton s.
I
: RetryCancel Retry and Cancel but ton s.
. gResu . lt. The
dialog wi d f MessageBox() ret urn s an_ obJ.ect -of class_D1alo
~The -- ~ w o ~ -- - - ~ -
6.10 shows
value of the ob· t d wh ich ·ha s bee n clicked . Table
epends on the but ton
some f th ~ec . dow s. .
. log wm
. s dia
o e. common valu es ret urn e d by var10u
sageBox
Table 6-10: Return Constants of Mes
\ I
As ter isk / ln for m ati on '
An ex am pl e to di sp la
1
Lo we rc as e le tte r i in
ba ck gr ou nd .
a cir cle w ith bl ue
e
y a m es sa ge , a ca pt io I
Ca nc el in di al og wi nd ow n, ic on of w ar ni ng an
is as fo llo ws . d bu ttons , OK &
M es sa ge Bo x. Sh ow f'H el
lo VB .N ET as pi ra nt s"
M es sa ge Bo xB ut to ns .O
KC an ce l, ·M es sa ge Bo xl
, "W elc om e" ,_ /J
Th e ou tp ut of ab ov e co ?o n.l tif ~r m_atio n)
de is as fo llo ws . .\ \
~ r,y l
l
(j,~..l._\.. ,J.)
0 He llo VB .NET a s p
i ran ts
• \ l
t>-.V_' \ / I
0\J,,
' •
.___o_ic_..J\ \ - t-l-/- ✓
Can ce.1__J
y ~
. punction.5 •
;{t-/11 (} fu n ct io n · gm · pu t in a modal d.
»~ 0 s u se r fior ge tt m
u,.;.... d ia1og
box. Th is
utB " () fu
.
nc ti on pr om pt tt on to ge t th e clos ed If th
fl 10P s.e r in p u t an d cl
ick o f a bu nu , ow e
Jnpu tB ~X th e u ox () fu nc tio n tum s the· vaJu
/t '11,e ·ts JOr n te r ke y, th e In pu tB re e
)J
wai b tt on or
pr es se s E. . er cl ic ks Cancel b ut to n, a ze ro-
·ot1 ct. If th e us
rtJ]lCt1 oK u as a. st n n g ob1e tBox() func tion is
J' clicK.S the t ex t bbx ro m pt ar gu m en t of In pu
Jimi·te r
vsef
11 : ("" ) is re tu rn ed . Only P be om it te d, bu t a comma d e
. tJtted en ts ca n .
st fl !l ! w ev er op ti on al ar gu. m t. T he pu rp os e of each argu.men t 1s
jIIP ..rh ' in g ar gu m en
r the co rr es po nd
}efl!,... nO
n,,dato.rY·us ed •o JI
lfl~
S JJ
shOiil ~ rable 6.12. J [, D EF AU LT J (, XPOS J (, YPO
oMPT (, TITL E
gil'efl in
ursoX( PR ox Arguments
Table 6.12: lnputB
rNP
Purpose
~ x.
AtguJlleDt
hi ch is di sp la ye d in the dialog bo
Nallle nt ai ns a st ri ng w acters .
This ar gu m en t co is ap pr oximately 1024 char
~ th of pr om pt
PfO!DPt The m ax im um leng e title ba r of
sp ec if y a tit le fo r displaying in th le
/Mandato!}' ) us ed to displayed in the tit
This ar gu m en t is n, fo rm na m e is
. If no title is give
I ficie the dialog window -
,
/Optional} ba r. em pt y fo r ge tti ng inpu t. However
1
xt box is displayed t for
- Default
By default, th e te
a st ri ng as a de
fault re sp on se ca n
textbox.
be pa ss ed th ro ugh this argumen
the sc re en .
, uppet edge of InputBox() function .
an d
- de in VB.NET to .
in p u t d at
.
e o f bi rt h us in g
clicks
tt on s. When us erP r · t
. Now, let's writeMco mg Y es an d N o bu · 01ec
dispJay age u . g essageBox() funct10n h av · · g MessageBox() ju nc ti on .
..
an b sm sm
·
Yshutton ' display ap pr op na te m
es sa ge ag am u
6.9 de .
ows the source co
Bo x()
g ln pu tB ox () an d Message
Project 6.9: Usin
11.. -
i-ubUc CJ118 ut Box
fnnlnp lick
nG et C A s E ve nt A rg s) Handles btnGet.C
Private Sub bt As Object, e
Dimdob A rin . - lick(sender
n· s St g
n
D ~ age As Times pa
ll1J res As n1·al ogResu1t
1Cf.J:j
doh = Jnp utB ox( "En ter you r D.O .B.", "Input")
age = Now() - Dat e.Pa rse( dob )
res = MessageBox.Show("Your age is
" & Ma th.R oun d(a ge. Tot alD a
vbNewLine & "Is it corr ect? ", "We I "
com e, ys I 365
MessageBoxlcon. Que stio n) Mes sag eBo xB , 01
Uttons '\r , ~
If (res = DialogResult.Yes) The n .1~1'l ~
o,
MessageBox.Show("Yes is clicked")
Else
MessageBox.Show("NO is clicked")
End If
End Sub
Pri vat e Sub btn Exi t_C llck (sen der As Obj ect,
e As EventArgsJ Han dles btn E .
Me.Close()
1tit.Clict
End Sub
End Cla ss
The out put scre ens are as foll ows .
,,--
msert/1
;; 'nput&> Function - 0 X Input X Welcome ,;·
&terywOO.B.
I
I GiOOB I
F
Your age is 48
Is it correct? Yes is clicktd
m J STRINGBUILDER CL ASS
The Sys tem .Tex t.St ring Bui lder clas s help
also allo ws con cate nati on of man y sma
con cate nati ng strin gs. Thi s clas s prov ides
strin gs ove r and agai n. The syn tax to
s in crii .tin g mod ifiab le strin gs. This class
ller stri ngs and is mor e effic ient meth
~I
Dim myS trin gBu ilde r As New Stri ngB uild The followm!
er(" Hell o VB. NET Asp iran ts!" )
Eith er a fully qual ified nam e can be use Create a Stnr
. d in the cod e or imp ort state men t can It
\ use d to imp ort Sys tem .Tex t nam espa ce.
in the .vb file. The syn tax to incl ude nam
This stat eme nt sho uld be the fiirs t staternen1 Append •n_
Insert• .
rrogi
epa ce is as follo ws.
l Imp orts Sys tem .Tex t R. Is a sir
elllove 11 h
.
I Cap acit y of a Stri ng refe rs to the max
stor ed in a Stri ngB uild er obje ct. Tho
imu m num ber of char acte rs thatb·ectcaJl
/;(
of
R_
.4 n
epJace th
C a
e Wor
ugh the defa ult capa city of an ° ~d '"cer p
Stri ngB uild er is 16, it can be spec ified 11ri/1$ CQc'- e.rfo ~s
and chan ged expl icitl y by d evelo p::n is w " of Sh . "J..lng
obje ct inst anti atio n. Cap acit y is diffe e owb
rent from the leng th of a strin g as Jen Utton
~
~
r,ctiolfS en t in a st ri ng
. In th e fio11ow.ing ex .
ra ct er s pr es ample, capa cin,
·{t-illtl' r 0[ cha . . ' J JS
p1d ant1at10n.
vrribe Ob·Yect inst VB.NET Asprr .
oJ fl · g
N ew S tr in gB ui ld er ("H el lo an ts !" 30)
o dt1 f1!1 . d As '
9ctil 3 . 13U1l er b. · th at it d
t to
S tn
B "ld
·n g UI er o ~ect
.
1s oe s not al lo cate si.ze fo r
re
se ((JJS.IJ.-if...'lg fu si n g a
cu rs th e new sp ace is all
tage o ty is re ac he d. W he n th is oc
-
itfl ci ' ocated
O dvaJ1
9 ,.,e capa
. . ub le d . T he common]Y used meth 0 d
1ne IJ ' d the ca pa ci ty 1s do - of
ntil an
If v e 6. 13 .
itse 8ucBllY ar e given in Ta bl
9utotil Jdef c1ass
Class
s of StringBuilder
Table 6.13: Method
striflgIW
Examples
D es cr ip ti on and
StringBuild er("VB.NET", 40)
D im sb A s New
ject of
ar ac te rs at th e end of th e ob
pe nd s ch ge ")
This m et ho d ap sb .A pp en d( " Pr ogramming Langua
F or E xa m pl e,
stringBuffer class. ringBuilder
or a st ri ng w it ~~ an ~bject of St ·
This method in se rt
s ch ar ac te rs
.I ns er t( 6, 1s a simple ") inserts " JS a
mple, sb
i1i c index. F or Exa
/nsertO at a spec
. le " at 6th posi
sIIIlP
tion.
m be r of ch ar ac te rs fr
om th e I
ec if ie d nu
ov es a sp emove(20 , 11) rem
oves
This m et ho d re m E xa m pl e, sb .R
er class. F or "t'
Remove/) ·ect of S tr in gB ui ld 2 0 th po si 10n m . a st nn .
g.
0 by om
11
characters st ar ti ng fr
ch ar ac te r at_ a ~pecified in de x. Fo
r I
~s a ~ ;~,ci ~e d places "simple"
This m et ho d replac P ro gr am m in g ) re
Replace/) lace("sim ple , S im pl e
Example, sb.Rep
am m in g' '
with "Simple P ro gr to a S tr in g obje
ct.
ui ld er ob je ct
er ts th e S tr in gB ring.
This method co nv S tr in gB ui ld er ob je ct to a st
ToStringl) er ts
String() co nv
For Example, sb .To on ly us ed
sh ow th e fu nc ti on al it y of co m m
ogra m in V B .N E T to
Now, let 's write a pr
StringBuilder functions
.
ed .
ing operat io ns ar e to be pe rf or m
The follow B .N E T"
it as 's b ' an d in it ia lize it to "V
Crea tea StringBuild
er object, na m e
Append "Programmm • g" to sb ob je ct
ta sk s like
oasoXES al og bo x co ntro l classes for various
"'oli'L al built-in di. _ ..- . - .
ces for colors, sele
cting fon ts
. s seve r age , pr ov id m g ch 01
lfJ1' F 011.tD1'al og, F1. leD1a . log, PrintDialogJ
NET pro~ n. =- ( ( ---:- _ ~
-;_;,-- vin g til-- e, -pn
to·ngs.,. C. czol:::ior D 1alog, the
VB- ,:;1e
--: 1g!!!---, sa ~ -- e se ;:; =, - .
l cl as se s w hich ar e inherited from
- .n di'alog box co nt ro
· • ·· •· - ileDialog an d SaveFileDialog
IJJl
oP;,.- hoosi.ng ~ at -
OpenF
the furt fi er p rovides
m
"d c - D
- 'a lag° er th ro ug h
~ ~
F
ilr
e cl as se s is ad de d to a Form eith
]as~ 1 ese
~ ial0g,c
., 1110nD ,_;:;....,,-- . al 1'ty of th ol bo x at design time or th ro
ug h
~ :;;.---- [u . nc t1 0n ntrols from th e To . l,
: ubclasses. Thedroppin g co k of an y vi
.
sual display of th e contro
s~ d in code. D._.ue to l~ th e Form
dragging an se c1asses
. the
..
0,! 11 PO ne nt jr ay at th e bottom of
.U
jnstantiat1Ilg nrP also vlaced in !: .h
,- . .
~ con_trols ~ r
bo~5.Q!ltr...Pl$_
. at ru n time. It 1s us ed fo
Designer wmdo}V, dialog
,,.. ·a1 O [unc tio
_
n displays
-- - -- -
gR es ult.A bbrt, D ialogResult.Cancel,
TheShowD1 ogof- -ty_ _
p~ DialogResult lik
e Dialo . . n in
.
v
al
ue pr ev io us ly W lth M essageBox() functio
returning a
on as discussed overridden by
DialogResult.Ignore and so ba se class an d is
in
() fu nction is available neve r th e
Table 6.10. The RunDialog is in vo ke d au to m at ic al ly , whe
s. This func tio n du ce s th e
dialog box control classe
of D ia lo gB ox controls no t only re
ShowDialogl) function is
called. Usage ay of pr es en ti ng
es standardized w
bu t also provid
forts, pl ic at io n. Various
development time and ef bo xe s to us er s of an ap
the form of di al og
~ommonly used tasks in
ialogBox controls are give
n as fallows.
j
l#tl ..._ R~
4'1tl1ct•
The fore color or back color of any conl:t-01 can be set using
example,
this Prop
e11y_
~
Pot
Labell .ForeColor = ColorDialo gl .Color
Label l .BackColor = ColorDialog 1. Color
Consider an example that drags and drops ColorDialo g control on Fo
its object named as ColorDialo gl and places it in the componen t tray rrn. It Cre<lt
name of ColorDialo gl object to clrDia and color of selected text of RichT. Change t~~
. .
to the color returned by Color property of clrD1a obJect. Before chano;,..., e~B~ contr4~
• t:,..... ig color . 01
check the value returned by D1alogRes ult enumerati on. This code also ' it rnll
stores
Color Property. The code is given as follows. Value St of
If (clrDia.Sho wDialog() = DialogResu lt.OK) Then
rtb.Selectio nColor = clrDia.Colo r
'where rtb is RichTextB ox
Dim er as Color = clrDia. Color
End If
6 .4 .2 FontDialo g Control
FontDialog control allows the user to select the font, font size and c
installed fonts on the local computer:} By default, it does not display ' o 1or fro
· th rn
ComboBox in the FontDialog. HoweverLS ·- e col
~ owColor prop½__r:ty_of the FontDialog controt
set to True for displaying color ComboB~ .J - ~ 15
Consider an example that creates an object FontDialog l of FontDialog class.
Change font of selected text of RichTextB ox control to the Font returned by Fom
property of FontDia object. The code is given as follows.
If (FontDia.S howDialog( ) = DialogResu lt.OK) Then
rtb.Selecti onFont = FontDia.F ont
End If
l
~
. . ~
.
. ~ction£ ly p e n m ss w n . The fI1
e IS d b
specifie Y the FileNam e
'{,,ittfl' file with re a d -o n
»#' we l
dapeflS ns .
plays li st o f files with rt f exte 10n, selects fiJ e an d load s the
l]pel~1•1. . g code dis ox.
pf'O foUowJ!l
Ri bTextB
1JJe r.Je joto c • - T ru e
d11 n -
seiec te . f\ddExtensio"r tf ' .
ne018· efaultExt --
0pel 18
. _p
) = D1alogRes
ult.OK Then
Dialo g(
oFueD · shoW . . eNarneJ
ope neD1a . i1 eD 1a .F1l
nF
fopeo F adFil e(ope
I rtb ,LO
gnd If y
piaJog control to se le ct a location and specif a name ilfo r
allows . th e u se r . E x t, FileName
and OpenF e()
6,4, 4saveveFi.leDi·a1og xtens1 o n, D e fa u lt
. . g. F o r example
he
S
a rop erties l1ke AddE .
O pe nF lleD1alo '
T
file The Pa similar way a s sh o w n m
· d.
saving a use in
are
rnethod rue
. AddExtension = T
58veD
1a.
"r tf '
saveDia.DefaultExt = DialogResult.O
K) Then
. h v·1alog() =
J{!saveD1a.S ow
ia.FileNa m eJ
rtb.Sav_eFile(saveD
End If
g
iaJog C ontrol ialo g th a t allows selectin
6.4,5 PrintD dows P ri n t D
rol is used to open th e Win P ri n tD o cu m ent component
APrintDialog cont m en t for p ri n ti
ng. T h e
wing a
er an d se ct ions o f th e d o cu
tP re v ie w D ia lo g helps in previe
aprint te r. Prin
ers to se nd an o utput to a p ri n
aJJows us
document. se t it s D o cu ment property to
class,
ject pr in tD ia o f PrintDialog lo g o bject is associa
ted with
Consider an ob . The P rin tD ia object
ob je ct of P rin tDocument class T h e p ri n t( ) m ethod of pdDia
p~Dia, an ngs.
en t ob je ct to ob tain PrinterSetti
Prial ntDoc~m F o r example,
c spdD1a Pri ntpage event procedure.
-
If IPrintDia Sh owD·Jalog = DialogResult.OK
) T h en
.·
Pn.ntDi a.Document = pdDia
. .
Pnntn·ia .pnn · terSett' _
D 1 a. P ri nterSettings .
. mgs - pd
PdD ·
~ ia. Pnnt(J
endIf
EII ARRAYS
Arrays are used to manage large number . of values of same data type. An arra\' ·
1
also called a fixed-size sequential collection of homogenous data elements i.e . 0 f sarn - s
data type. All the elements are given a common. . . occupy
name and d contiguous mernont
locations. These elements are accesse d usmg a numenc · ·· d
m ex n u m ber which 1. .
S alsr
known as subscript number. Elements can b e o f pnm1tive ata types or obJ·ect s. u
/ ctl---- 23
r11 12
[2] 45
r31 65 Values of
Elements of r41 34 elements
demoArray
[51 78
starting from
0th to 9t11 index r61 4
[7] 67
[81 89
r91 33 -
EE ONE-DIMENSIONAL ARRAYS
Arr h · • 0ne·
d. An . ay avmg one mdex is called one-dimensional array. The elements
imens1onal array are referenced with single index.
r ·.~-/. ~
t•~~: f : : : :t 111ensiona!Array
·~ '~ \ ~ l
. /vJ~7-M ~ : ,,~,
,
, .l
pe[i{rhi;onal arrays are declared hke a smgle vanable using eith er 0 im .
or
S· diJ1lens, °', ~-ai:r.a ,y.....cau.J2.~_us
b
e_d throughout
.
an aoolicatio
--
hil
n _w e
011e- nt. A~ . only m a local proce d ure or
tatei1le ·flg:..-f>.im.- st.ate.ment can e used . - -
1.!iC s ,.,.-ed.,...USl ·· .
ptiv y dee1c:u. be initialized durmg declarat10n. The syn tax to declar e a one-
arra s earl
p.rraY . VB.NET is as follows. YL-vU a. .M,l'i .. u _ /.J-luJ
al a.rraYin ,- _.J - - vl.Y-" V-J -
111
0
diJ11e!1 !ly Narne>(n) as· <Data Type> or .Q ~ ( J
1
..,, t.Arra - _ (-) s <Data Type> = New <Data Type>(n) or
D'"' Na.me> a ' "'
Di[!I t.ArraY-N~e>0 as <Data Type>
' ,Array_ ( )
Di[!I N w <Data Type> n
Na.J11e== e
ArraY- . d (upper bound) and size of Array is n+ 1
,11, re n is Jast in ex b d) . .
\v,,e . d' tes the last index (upper oun m an array mstead of the number of
11111 1ca . .
Here, ay Its first element 1s at zeroth (lower bound) mdex and is referred
in the arr .
eJernents (O) the second element is r.eferred as array_Name (l ) and so on. So, th e
as array_Name a ' is one more than the number specified during declaration i.e. n + 1.
· d· h h b·
length of an arr dy in declaration statement m 1cate t at t e o ~ect typ e is· an array.
theses use
paren t declare an array using different ways are as follows .
The examP1es 0
. ( ) as Integer ' Declares an Integer array of 3 elements ·
Dim mtArray 2
Dim dbJArray(2) as Double ' Declares an array of Double data type with 3 elements
Dim intArray As Integer() = New Integer(2) {} ' Declares an integer array of 3 elem ents
8.2.2Initializing an Array
Arrays can be initialized when they are declared. The elements are specified using
braces 1 } during declaration. The examples to declare and initialize array using
different ways are as follows.
DlmintArray() as Integer= {10,20,30,40 ,50} ' Initializes array of 5 elements
Dim intArray(r As Integer = {4, 8, 12} .
Dim intArr ._______ _
. ay As Integer() = New Integer(2) {4,8, 12}
DimstrArra () . ...__
. . Y As Stnng = {"Lipakshi" "Arnav" "Jannat" "Anupam"}
Dilll lllIXArr ' ' '
'Wh ay() As Object= {"VB.NET" 2O18D IOUI "I"C} .
ere D UJ , , ,
' and C repres t d .
If the v en ata types of Decimal, Ulnteger, Char respectively
spec'fiI alues are s .fi .
arr iect, then th peci ied at declaration time and upper bound value 1s not
ay Ii
the · 0wever if th
'
e number of th alues specified determines the upper b oun d f an
e user
e v
'fi h
°
re sh0
l1si Uid be n + . . . speci ies both upper bound (Let n) and initial values, t en
1 · · · · 'al' d ·
gnrnent 0Perator initial valu es. Ind1V1dual array elements can be m1tl ize usmg
as follows.
r intAr ray(O )= 10
intAr ray( 1)=2 0
intAr ray(2 )=30
strAr ray(O )="So ni"
strAn ;ay( 1 )="G eet"
-·
istrA rray( 2)=" Latik a"
strAr ray(3 ="Na veet"
strAr ray(4 )="S onia"
strAr ray( S)=" Priya "
Next
Mes sage Box.Show (inta rray( i))
"' '
~
De scr ipti o n
New In teg er (2) {4 , 8, 12!)
propettY
intA rray . Min () r etu rns 4
Naflle i - -_ f tion ret urn s min imu m val ue
~
Thi s unc
in an arr ay.
MiJ10 intA rray . Ma x() r e tur ns 12
- . f tion ret urn s ma xim um val ue
Thi s unc
~ in an arr ay.
------
MatO intA rray .Le ngt h r e t urn s 3
. erty ret urn s tota l num ber of
Thi s pro p I
ele me nts in an arr ay.
I
1,ength
Array .Rev ers e(in tAr ray)
Thi s [un ctio n rev ers es 8:-° arr ay. rTh
Array.Reverse() rev ersed arr ay is sav ed 1n sam
e arr
e
ay. I
ay. Dim new Arr ay As Int ege r ( )
Trus [un ctio n ma kes cop y.o f an arr int Ar ray .Cl one ()
Clone()
Arr ay. Sor t(in tAr ray )
~ Trus fun ctio n sor ts an arr ay. The
Array. Sort H stor ed arr ay is sav ed in sam e arr ay.
the Dim arr( 2) as Int ege r
Thi s fun ctio n res ize s dim ens ion of
Array.ReSize() Arr ay. ReS ize (arr ,4)
arra y pas sed to it.
e to do
and pra ctic ally the con cep t of one -di me nsi ona l arr ay, wri te cod
To underst
the following.
On Lo stF ocu s eve nt
Draw a TextBox (txt _nu mb er) to
get siz e (m ax 10) of an arr ay.
um eri c. If Tex tBo x is
t this Text Box, ens ure tha t Tex t box is nei the r em pty no r no n-n
lank or non nu
.
. . ert1. on poi. nt sho uld rem ain the re.
- men c, ms
On Lo stF ocu s
Draw anoth
of th· er
T
ext Box (tx t_e lem ent s) to get ele me nts of the arr ay.
event eri c. Ad d the
eist; extB ox, ens ure tha t Tex tbo x is ne ith er em pty no r no n- num
vaJue ofT ion poi nt
oxh to a Li st con tro l. If Tex tBo x is bla nk or no n-n um eri c ' ins ert
should rezn:;~
-.u,it ere.
On click of S
ilnd dis I um and Av era ge B u t ton s, cal cul ate su m an d ave rag e of arr ay ele me nts
On . Pay results . T xes to Fal se.
chck In ext Box the ena ble d pro per· ty of Tex tBo
respec t· of Clea r and E . es, and set ·
XJ.t b tt val ues an d clo se the win dow
1veJy
· u ons , cle ar all the
p .
roJect 8
.1 shows th
e sou rce cod e.