0% found this document useful (0 votes)
15 views25 pages

Chap 6 and Cha8

The document describes various methods for manipulating date and time in VB.NET, including adding days, hours, minutes, seconds, months, and years to a Date object. It also covers comparison methods for determining the relationship between two dates and formatting functions for displaying dates and numbers in different styles. Additionally, it includes example code demonstrating how to implement these functions in a VB.NET application.

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)
15 views25 pages

Chap 6 and Cha8

The document describes various methods for manipulating date and time in VB.NET, including adding days, hours, minutes, seconds, months, and years to a Date object. It also covers comparison methods for determining the relationship between two dates and formatting functions for displaying dates and numbers in different styles. Additionally, it includes example code demonstrating how to implement these functions in a VB.NET application.

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

Ret urn s date tirn

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

it. It retu rns a Bo


are equ al or n e~
1
ot. F'or
DateTime) example, Dim Ob jlas DateTime
Obj 1=" 22- 12-201 8"
False
Date.Equals(currDate, Objl) reh iins
For example,
i String(dateObj as Converts dateTirne object to string.
dat eTime) 02- 10- 201 8 13:0 2:4 3 (as string)
control lJ
wri te cod e in VB .NE T to disp lay the cur ren t dat e in a Label
Now s and upcta~e Se
to acc ept yea rs, mo nth s, d~ys, hou rs, mi~ ute s and sec ond
Tex tBo xes u the
e fun ctio ns. Also che ck wh eth er Pdat
wit h val ues acc ept ed usm g Dat
cur ren t dat e . 65 h th code. ed
tha n cur ren t dat e, sam e or late st. ProJect . s ow s e sou rce
dat e is old er
Project 6.5: Using Date Functions

Public Cla n frmDateMethods


Dim currDate As DateTirne = Now()
Dim updatedDate As DateTime
Dim dd As Object
ntArgs) ff
adfsender As Object, e As Eve
Private Sub lrmDateMethods_Lo lllldlea
MyBase.Load
updatedDate = currDate
e and time is " + cur rDa te
lbICurrentDate.Text-= "Cu rren t dat
e is " + upd ate dD ate
1b1UpdateDate.Text = "Updated Dat
ate d dat es are equal"
1b1Compare.Text = "Current and upd
End Sub
sender As Object, e As EventArgs) Handles
Private Sub btnUpdate_Click(
btnUpdate.Click
updatedDate = currDate
If (IsNumeric(txtMonth.Text)) Then
onths(txtMonth.Text)
updatedDate = upd ate dD ate .AddM
End If
If (IsNumeric(txtYear.Text)) Then
t)
updatedDate = updatedDate.AddYears(txtYear. Tex
End If
If (IsNumeric(txtDay.Text)) Then
ays(txtDay.Text)
upd ate dD ate = updatedDate.AddD
End If
If (IsNumeric(txtHours. Text)) Then
our s(tx tHo urs Text)
upd ate dD ate = upd ate dD ate .Ad dH .
End If
mi
,_,,.;,,~ . txtMiJ1ute. Text)) Then t)
nsNi.J!!leric( d tedDate.AddMinutes(txtMinute .Tex
If,. dDate "" up a
tlpdate
_god If . txtSecond.Text)) Then
s(txtSecond.Text)
If ~sNi.J!!leric( "" u datedDate.AddSecond
...ti tedDate p
tlY""a
_god If xt ::= "Updated Date is " + up~ tedDate
...ti teDate.Te
Jblv..,...a compareTo(currDate) > OJ Then
...tlatedDate.
T xt "" "Updated date is Latest"
If {Uf""'
1co111pare. e
Jb atedDate.CompareTo(currDate) < 0)
r"
gJseif /upd Text ,::: "Updated date is olde
JbJCo111Pare. -

Text::: "Current and Updated dat es


are equal"
gJse
JbJCo111Pare.
gnd If
) Ha ndl es btn Ezi t Cli ck
JJ!d sub b bta.E.dt clic k(s end er As Object, e As EventArgs ·
priflte Su -

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

(i) Built -in Format Functio


ns
) function is as follows.
Th e sy nta x of bu ilt- in Format(
)
Fo rm at (object, "style value"
is for ma t style.
te or oth ers an d "style value"
Wh ere ob jec t is nu mb er, da
given in Table 6.6.
Th e lis t of sty le arg um en ts is
ns
nts tor Bui lt-in Format Fun ctio
Table 6.6: List of Styl e Argume

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

The output is as follows.

iJj Format Functions - D )(

/567364.2384 Formatted resi.41s are :·


Etier~V i!loe General Nuri>er Format is 567364.2384
Ftxed Format is 567364.24
_ ___.I
o._2384 Stcl'ldard Format is 5.67.36424
Etier V,Jue for percertage IL- wrency Format is~ 5.67.36414
Pe,ce,t Format is 23.84%
General ~e Format is 02-1~2018 18:44:51
Go ] Ed I Long Date Format is 02 October 2018
Short Date Format is 02-1~2018
Long Tme Format is 18:44:51
Short Tme Format is 18:44

(ii) User-defined Format Functio n


The developer can format the numeric or date/ time data in a specific format. Th
developer can also define user defined formats using combina tion of pre-define:
formats available in VB.NET. User Defined Formats are also known as custom formatS.
The syntax is as follows.
Format (object, "user's format")
The Table 6.7 lists some common ly used format specifier for user defined Formats.

Table 6.7: List of Format Specifiers

- - -- -
Specifier Description

d Displays the day of the month (between 1 and 31)

dd Displays the day of the month (between 0 1 and 31)


dddd Displays the full name of the day of the week
M Displays the month (between 1 and 12)
MM Displays the month (between 0 1 and 12) -
MMM Displays the abbreviated month (Jan-Dec)
MMMM Displays the full month
yy Displays the year in two digits (00-99)
yyyy Displays four digits year
h
hh
H
Displays the hour (between 1 and 12) in 12 hour format
Displays the hour (between 0 1 and 12) in 12 hour format
. 24 h
Displays the hour (between 1 and 24) m £
our ormat
---- I

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 .

~ Cu stomized Dat e Fo rmat D X


'
dd-MMMM-yy :02-October-18
dd-MMM :02-Oct
Show Cultomized Date MMM-yyyy :Oct-201 8
YYYY-MM-dd :2018-10-02

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

Dim strl As String= "He said, 1111


The earth moves round tht Sun """

·
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

manipulate strings as listed in Table 6 .8 .


a
Table 6.8: String Functions

Description and Example


doll Nallle Let strVal = "Y.1;3:~ET Programming"
f1JOC ----+-------,,,---:---:---- ~----:---:--- - - - - ~
The len() function returns the length of a String as an
(strVal as Strln~ integer value. It also includes the empty spaces of a
/ string. For example, Len(strVal) returns 18.
or -, r.,engthO Length() method with string object is also used to find
strV'(JJ• ; · ' length. For example, strVal.length() returns 18.
The Right() function takes out n characters starting from
VisualBasic.~ hl:-
. rosoft. 7/ the right"(" of a String. For example,
M\a1
(str
as string, n) '-✓·
· Microsoft.VisualBasic.Right(strVal, 5) returns "mming".

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

. ft VisualBasic.Mid The Mid() function retrieves a part of text from a given


M1croso . String where s is the starting position.Jrom left side and n
(String, s,n)
is the number of characters to be taken out. For exam pie,°'
----,--"'__.
.".' :
Microsoft.VisualBasic.Mid(strVal, 3, 6) returns ".NET P".
The Trim() removes the leading and trailing spaces from
the String. For example,
Or
strVal.Trim() / Trim(" Arnav Arora ").Length() returns 11.
If trimmed value is to be stored for future reference, store
the returned value to some variable. For example,
Str 1 = Trim(" Arnav Arora,")
Str2 = strVal.Trim()
/ The Rtrim() trims the empty spaces from the right of the
String. For example,
Rtrim (" Amav Arora -").Length() returns 13.
,The Ltrim() trims the empty spaces from the left of the
String. For example,
Ltrim (" Arnav Arora ").Length() returns 12.
Instr (n, original String, The InStr () returns the starting position of an embedded
embedded String)
String within the original String. For example,
Instr(l,strVal,"P") returns 8.
Microsoft.VisuaIBasic UCas The UCase () converts the string to capital letters.
e(String) .
UCase(strVal) returns "VB.NET PROGRAMMING"
lrf_f_l_____ __~ - - - -- - - : - - -strin -itilt-ni '
- . - -- -B
Microsoft.Visua1B7sic.ase the LCase () converts th e " bg to small lett ers h
(String) / example, LCase(strVal) returns v .net progratnrnin~ . re,
Chr(code as Integer) The Chr{) returns character or symbol for an Asen c
Some of the characters may not be ~splayed as O(!e_
represent actions such as the pressing of a keyth~
producing a beep sound. For example, o►,
Chr(65) returns 'A'.
Chr(122) returns 'z'.
Chr(37) returns %'.
The Ase() function returns ASGU code for a character Or
Asc(code as Char)
symbol. For example,
Asc("A") returns 65.
Ase("%") returns 37.
A string c8:11 be converted to an array of type Char. For
ToCharArray()
example, Dlill c As Array= strVal.ToCharArray()
(to be used with String)

Space(number as Integer) The space function is used to return a string containin


the specified number of blank spaces. For example, g
Dim blankStr as String= space(S).

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

Microsoft.VisualBasic):£ase the LCase () converts the string to small letter


" b s. P
(String) / / example, LCase(strVal) returns v .net programtning"_ or

Chr(code as Integer) The Chr() returns character or symbol for an Asen


Some of the characters may not be ~splayed as c:e.
represent actions such as the pressing of a key ~ O·1
producing a beep sound. For example,
Chr(65) returns 'A'.
Chr(122) returns 'z'.
Chr(37) returns%'.

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.

ToCharArray() A string can be converted to an array of type Char. For


example, Dim c As Array= strVal.ToCharArray()
(to be used with String)
Space(number as Integer) The space function is used to return a string containin
the specified number of blank spaces. For example, g
Dim blankStr as String= space(S).

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"

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 ASCll
value of the first string is higher; it returns -1 if the ASCll
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 = "Arnav"
Dim str2 As String
Str2= "ARNAV"
Dim result As Integer
result= String.Compare(strl, str2)
result= String.Compare(strl, str2, T~e)
., in punctions
»1111t~
t .
tion Compare sta tem ent can be s e ~~~
~e Op . to Bin
comparison me tho d to use wh en com
of ea Phanng string ~ orA1'e>rt • It d t.,
default the num eric Unicode. val ue c char ata. ~
pares r in th bin- ec~ ..
cha rac te basedacte
corll . on compares eac h Unicode e . ~ -er..._ ,s th
n its . strill g v'fJ ~ ~
r 0
paflS •
corll u}ture. It can be cha nge d similarly as In case of O . 1e)(icai , %iJe ¾
current c the fu . Ption expJjCJt. niean in a ttt;
Jet's write code .in VB.NET to sho w nctionali (Ch g 1n ,
NoW, ty of co a.Pter t.'lt
. s Perform followmg ope.rati ons . lllrnonly 2I
{unction · . . . .
llSed s1,l!lg
"VB.NET Programming"
create a string object and m1tial12e to
from 5th h
. d its length and• stri ng sta rtin g c aracter f
F1I1 cha rac ter s from 3rd p .. roill Tio1-.
ters from left, stn ng-of 6 os1tion (left) &it, StJin
charac . anct Posiu g'fof>• 5
·ng obJect. ·
on of
stn .
low erc ase in
Convert string object to upp er cas e and
Replace VB in string w_ith "Visual Basic"
ze to " Arnav Arora ,,
Create another stri ng object and initiali
ng length() method 0 f Stnng .
Find its length and len gth afte r trim usi
trim of string
Find its length after left trim and rig ht
Find the character having ASCII v~u ~
_?f -~~-..
operati .
After performing all the ope rati ons , display the output of ons in a label on
, the sou rce code.
click of Show button_.· Project 6.8 sho ws
Project 6.8: Using String Functions

Public Class frmString


Private Sub btnShow_Clic.k{sender As
Object, e As EventArgsJ Handles
btnShow.Cllck
Dim strVal As String
Dim strVa12 As String
Dim ret_string As String
strVaI = "VB .NET f'.rogramming"
al & vbNewLine
ret_stnng = "Th ~-original string is " & strV
(str Val ) & vbNewLine
ret_stnng = ret_string & "Length is " & Len · ht is "&
ret tring = ret_string & "The String starting from 5th character from ng
. _sv·
M1cros oft
· rsuaIBasic.Right(strVal, 5) & vbNewLine
1 fi · " &
ret Strin g · & "The string of 5 characters from e t 1s
-- ret- 8 tnng
Mier f-t.VisuaIB ·
oso asic .Left(strVal 5) & vbNewLine · · (left) is "&
. ret_stnn = ret_Stnng . " ' from 3rd pos ition
M1crosoft v· g & The string of 6 characters
. rsuaIBas re.· M'id(strVal, 3, 6) & vbNewLine
[la
·{ ·n iunction.5
»''' t-1 .ru nct ion s
,.1 otb tr 'd es two use ful fun ctio ns, MessageBox anct 1npu m 0
6. i;-f proVl window ope ns d . r
wa its 1or use r res pon se· After th
x. Using th ese
;;, ._
I3.Ni an
I/ .
d1i:1uog closed. Th ese two func t10 ns are descri bed e User res
11s, a . as follows P<mse
60 .,rindoW is ~ - - - _,, ,_;,- .
ftJflC
&~~w• /~
we Bo"() Function
me ssa ge in dialog wind ow at run .
ll)t,feS gessagebox() fun ctio n dis pla ys a
511
. tune . Thi
l e e d-1 window wh ich blo cks all oth er act ion s in the applica tio . s
· a-rn° _ ~ - · 1
t can J>e use d wit h n Until it 15
ai
·ridoW 1s Th ere are aro un d2 1 opt10ns; tha . a Messa 8ox(). a\'
,vi dOwn- - . . y any capt:!Qn . Ho wev er a ct , ge
.
ed . dow does not dis pla , ' eiau.Jt OK
. . . . M button
c105
.
this Win
dialog win dow wh ich 1s clicked to clo~e the window. The
defa1.ilt, ton ~(u sin g various Messaessa ge.Boxl) is
appears 111 tbde tO display me~ ssae-e, cap tio n, but geB -
.- -
oxi con con stan ts). _:__ ~..,oxBuUerr
0

allYuse d . fonnation ico ns (us mg Me ssa geB ~ -·


gener . .
tant s) an in
1s as follows .
cons . t fonn of MessageBox() fun ctio n
Jhe sunP1es ·
T asp ira nts ") ' to dis play messa
ge on]
Show("Hello VB:NE . . . y
MessageBox. . . . . as foilo
dialog wm dow is
display a capt10n m title bar of ws.
The syntax t o
"Welco me ")
Show("Hello VB.NET asp ira nts ",
B
Message •OX oiven . T
constants i::,•
eBox() [un ctio n can us~ any _o_ne of the but.ton . in able
ag - - - - win dow . The se b
The Mess t of MessageB· ox() dialog Uttons
- d. Jay various but ton s as par
69 to 1sp
· ail ble ~ ~ ssageB-oxB utt on s class.
area~ a -
stants
Table 6.9: MessageBoxButton Con

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

Button Options Integer Value Constants (DialogResult)


OK Ret urned
I DialogResult.OK
2 DialogResult. Cancel
3 DialogResult.Abort
lf ll
- - r - - -q::--- - ~ ~ Built-ht b..
ltct:
Di al og~
Re su~
Re try ~ .... 11
lt. Re try- - - 10lt&
~gnore \ 5 Di al og Re su lt. lg no re
Yes
No
lI 6 Di al og Re su lt.Ye s
7 Di al og Re su lt. No
An ex am pl e to di sp la
y a m es sa ge , a I
fo llo ws . ca pt io n an d b~ ~t on s
in di al og w in do .
'--i
M es sa ge Bo x.S ho w( "H ell W lS ¾
o VB.NET as pi ra nt s" ,~
W elc om e" ,_
M es sa ge Bo xB ut to ns .O
KC an ce l)
If (re s= Di al og Re su lt.OK
) Th en
M es sa ge Bo x. Sh ow ("O K 'w he re Di m re s As Di alo
is cli ~k ed") gR es u1 t
E\ se
M es sa ge Bo x.S ho w( "C an
ce l is clicked")
En d If
Th e M es sa ge Bo xl ) fu nc
tio n al so di sp la ys di ffe
di alo g wi nd ow fo r re nt ic on s al on g w ith
be tte r vi su al di sp la m es sa .
M es sa ge Bo xl co n. Th e y. Th es e ic on s ar
co m m on ly us ed ic on s e av ai la bl e ~~ in the
ar e gi ve n in Ta bl e 6 .1
1 . _/ class
Ta ble 6.11 : Me ssa ge Bo
xle on Op tio ns
Ic on O pt io n
De sc ri pt io n of Ic on
None
Er ro r /H an d/ St op
No sy m bo l. Icon ---
Sy m bo l X in a cir cle w
ith re d ba ck gr ou nd .
Qu es tio n
Qu es tio n m ar k in a
cir cle (u se d on ly
0
•&
ba ck wa rd co mp ati bi lit y) fo r

Ex cl am at io n/ W ar ni ng
Ex cl am at io n sig n in
\I a tri an gl e wi th ye llo
w
ba ck gr ou nd .

\ 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

/Optional) displaying in the nt er ed . However,


a numeric
ho ri zo nt al ly ce
pu tB ox is of left edge of the
Inpu tBox
By default, the In se ts th e di st an ce
which
Xpos v~ue ca n be pa ss ed
of the sc re en .
/Optional) from the left edge d approximat ely on
e third
al ly po si tio ne
is vertic ss ed
By de fault, the In pu tB ox ow ev er , a nu m er ic value ca n be pa
Ypos
the way down th
e sc re en . H ed ge of th e InputBox
from
of of up pe r
/Optional) rtical distance
which se ts th e ve I

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

1~2211_0!1_9111_ _ _ _ __ _~1 Yes / / No or J ReplaceO

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

dec lare and initi aliz e Stri ngB uild er strin


od of
bett er perf orm anc e for con cate nati ng variou
g is 85
; Now, let's \1
StringBuiJder
:::-1
follo ws. ft.

~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

lnsert "is a . " te xt o f sb ob je ct


R simple at 7th location in
emove 11 ch po si ti on
R aracters from 20th
epJace th " . in g''
e word "simpl e" W.lth si m ple pr og ra m m on
After e .
o e . . u tp u t o f oper at io ns in a La bel
l th e
clickof p rformmg alP . y th e o
P ra tw ns , di sp la
Show button s th e so ur ce co de
.
. roJect 6. 10 sh ow
[I 5trin98uifder function
. . I String is VB. .NET
ongrno .
NET progromming Progra mming
VB - ET is a sim ple
. pl
VB .N T is a s1m .
NE e
Sim ple Pro gramming
VB - ET is 8
VB .N

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.

6,4.I ColorDialog Contr


ol
ColorDiaJo ntrol class is bo x w in do w·, It allows us er
lose] ~ c~ l · ~ us e
d
to ope.r:i a color di al og
sired- co colors .
~ or irom av.ru'1 able colors an d cu st o m • .
· . l'he Shown·~~() . ult ob 1ect
opens CO1orDia . re tu rn s D1alogR es
~ m ethod log bo x an d
icating th ass.
db
So,itsvai e button presse y User Th . D1 'al ogBox re tu rn s an ob je ct of Color cl
Ue IS st0
red in an ob· · ts
DinJcr
n· ~ect of Color class. Fo r example '
as Color" Col
or ialogl.Color

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

6 .4 .3 OpenFileD ialog Control


OpenFileD ialog allows the user to select and open a file. The user can check if the
file exists before opening it. The OpenFileD ialog control class inherits from the abstract
class FileDialog.
Its AddExtens ion property is used to indicate whether the dialog box_ sho~~
automatica lly add ~ e xtension to a file name if the user omits the extension. ser
CheckFileE xists property is set to true for displaying warning if file speci~~~!y~ et
does not exist. By default, it is set to false. The FileName p.rop er ty i:;, _u s e a ~ ! 5
~ _ c, 0 ~ g the file name ~elected in- th.~- F Jiliialo~. ]'he Chec~ _j!..2ds!· 'fhe
pt.._operty is used to display ~~in~~~~ the user specified path ~oes; ~ penFile~
QefaultE.x t property is used to get or set the default file name extenswn.

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

There are o f d o cu ments such as


n g
Pri
ntersetr many contro. ls related to th e p ri n ti
JIJgs, PageSetU ri trol.
PD1alog an d P ntPreviewCon
r-
The follow.ing co d o p en s a p ri n t p re v
. o ·a
e
PrintPreview 1 lo g l ShowDialogO
·
ie w w in d o w .
'o p e n th e p ri n t
~~ ~
p re v ie w
Now, l et ,s w ri te VB .NET co d e to
following fu nc ti on d e m o n st ra te th
al it y • e u se o f n ·a 1
1 og B o){
U se a RichTextBox
to en te r th e te x t, controls,.,..,.
D ra w O pe nD ia lo . sa v e th e te x t a n
g, SaveD1alog, P ri . . d lo a d th t
.
co n tr o ls o n F o rm n tD 1 al o g , P ri n tD e ex t of a file
ocument C
u se following b u tt , o1or D1.a1 F
0
o n s fo r ta sk s a s g, on~
fa ll o w s.
Color : for ch an g in
g co lo r o f se le c te ·
F o n t: for ch an g in d te x t o f R ic h T ex
g fo n t o f se le c te tB o x
P ri n t: for p ri n ti n d te x t o f R ic h T ex tB o x
g th e te x t o f R ic
Save: for sa v in g h T ex tB o x
th e te x t o f R ic h T
ex tB o x
Load: for se le ct in
g a file a n d lo a d
E xi t: for ex it in g th e c o n te n ts
o f file in RichTex
tBox
P ro je ct 6 .1 1 sh o
w s th e so u rc e co
d e.
P ro je ct 6.11 : U si
ng O ia lo gB ox C on tro ls
' T h is co d e u se s cl
rD ia , F o n tD ia , sa
' ColorDialog, 'F v eD ia , p ri n tD ia
o n tD ia lo g, S av eD a n d o p en F il eD ia
ia lo g, P ri n tD ia lo objects of
Im p o rt s S y st em g a n d OpenFileD
.D ra w in g .P ri n ti ialog respectively
ng
Public C lu a fr m
.C o lo rF o n tD em o
P ri v a te S u b b tn
E x it_C li ck \s en d
er A a O b je ct , e A
Me.CloseO a E ve n tA rg s\ H
an dl es btnExit.CU
ck
BndSub
P ri v a te S u b b tn C
ol or _C li ck \a en d er
A a O b je ct , e A ell bt nC ol or.cUck
If lc lr D ia .S h o w D s E ve n tA rg s\ H an es
ialogl) = D ia lo g R
es u lt .OK) T h en
rt b .S el ec ti o n C o lo
r = cl rD ia .C o lo r
E n d If
Bnd Sub
P ri v a te S u b b tn
F o n t_C li ck (a en el
d er A s O b je ct , A s E ve nt A r& •l H an le • btnFont,cUck
If lF o n tD ia .S h o e
w D ia lo g l) = D ia lo
g R es u lt .O K ) T h en
rt b .S el ec ti o n F o
n t = F o n tD ia .F o
nt
E n d If
End Sub
P ri v a te S u b b tn ,-
S a ve
m Working witJ;
Atta,
In some scenarios user may need to proc!ess.1 large number of data ele .9-1
' . r l rnent
. s uf
same type like hundreds of variables for stonng emp oyee
b O
f . of an organizat1on
codes
becomes difficult to declare and process a large num er umque variables . 1n s · It
cases, arrays are used for processing elements of same data type collectively. llch

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

Arrays help in writing small . codes as collections


. of values can be repres ented b•·
same name but different subscript. Repeating same code for different su bscri t ·'
, . . . P sm~
the code simple
. and . sma110JTays
. are also efficient m terms of m emory man agernen·
and processing. Ind1V1dual elements of arrays are accessed through index. All the·
. .
~lem~nts of an array are stored. m contiguous memory locations . In VB .NET, all arra ·s
mhent from the Array class m the System namespace. The Figure 8 · 1 sh ows the J
concept of an array by storing an array named as 'demoArray' having 1o el ements of
Integer data type.
Figure 8.1: Understanding Arrays

demoArray (Name of array)

/ 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

Dim StrArray(2) As String 'Declares a String array of 3 strings

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 "

8 .2 .3 Acce ssin g Elem ents of an Arra y


After an arra y is decl ared and initia lized the next
. Th st { · .
store d m an arra y. e loop , ep is to retn eve th
. ing cont rol cons truct s are used t e Value
,, o acce
array . The follo wing code show s how ·valu es can be ret • d ss. all elements of ans
For .. . Each loop . neve usin g Fo N
r. .. ext anct
Dim intar ray As Integ e\ 0 = New Integ er(2) {4,8, 12}
'arra y decla ratio n
For i As Inte ger= 0 To intar ray.L engt h - 1 step 1

Next
Mes sage Box.Show (inta rray( i))
"' '

Dim inta, rray As Integ er() = {lQ, 30, 50}


/ ')
'arra y decla ratio n
F\>t Each i As_ I_n tege r I.~ int?- IT~
Mess ageB ox.sh ow(i )
Next
For. .. each loop is pref erred whe n each elem ent of
an array is to be accessed. It is
not prefe rable for assig ning valu es to array elem
ents or comp aring two arrays.
More over , elem ent (i) fetch ed usin g For. .. Each loop
shou ld be of s~e data type as the
elem ents of an arra y.

8 .2 .4 Res izin g an Arra y


A one- dime nsio nal arra y can be resiz ed i.e. can be · size
mad e bigg er or smaller in
The synt ax to resiz e arra y is as follo ws.
Arra y.Re size( oldA rray, 3) whe re oldA rray is chan ged
to size 3 · thr
This meth od alloc ates a new arra y with the spec ified . . leme nts fro!ll
size, copie s e If the 11e"'
old arra y to the new one and then repla ces the old ·th th new one.
array wi e d 'If the 11ei
size is less than that of origi nal array , the elem ents h
at t e en d are remo ve .
the end.
size is grea ter than that of origi nal array , the new elem
ents are adde d at
~ .
m
,,,L.~rrays
ff'IIII • an d P rop ert ies . .
l.;.fJ1
nct 1on s . te d wi t h an in sta n ce
11o"'r" use ful fun ct1 0ns and pro per tie s a sso cia
..-<flY f'l1
7, 5 JV- •des rna nY
8, · "1.-,.,r proVl . Tab le 8. 1. .
v13.i,P • s sho wn in of an A rray s
iJJ1 a.rra.J a. Tab le 8.1: Fun ctio ns and Prop ertie
of
Exa mp le
(Di m intA rray As Inte ger () =

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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy