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

Chap 4

The document discusses the use of CheckBox and RadioButton controls in VB.NET, detailing their properties, events, and transition orders. It provides examples of how to implement these controls in a form, including displaying the status of selections and handling events. Additionally, it covers the PictureBox control for displaying images and the Timer control for executing code at specified intervals.

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

Chap 4

The document discusses the use of CheckBox and RadioButton controls in VB.NET, detailing their properties, events, and transition orders. It provides examples of how to implement these controls in a form, including displaying the status of selections and handling events. Additionally, it covers the PictureBox control for displaying images and the Timer control for executing code at specified intervals.

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

~[~ usea controls of ~.

NET m
event is ·raised. on clicking a CheckB0 ~ control.
cUck This event is raised on a change in th · .. _ _
,,stateC h~ d proper ty of the CheckB ox control · e value of the CheckS tate
cbec~ L
• T a ble 4.6B.
oiven m
is ~
rne order of firing for three above mentio ned event ;
Table 4.6 B: Transition Order of CheckBox Events

Order
- TraJl&itioD
Checke dChang ed, CheckS tateCha nged, Click
L----j ;d to checke d
uncbeC CheckS tateCha nged, click
1..::::::----:-.to grey
cbecked Checke dChang ed, Checks tateCha nged
~ d
GreY to unchecke usmg three CheckB oxes for three medals (G Id
O
I~ design a Form m VB.NE T
b I d. I '
and Bronze) . Place three Ia es to tsp ay status of each of the CheckBox. On
Now,
silver
. f Checke dChang ed event of each of the CheckB ox, display status in respect ive
finng o Proiect 4. 7 shows th e cod e.
labels. The 'J
Project 4.7: Using CheckBo x

Public ctass fnnchk s btnEld t.Cllck


p,ivate Sub btnEldt_Cllckfs ender M Object , e M EventArgs) Handle

Me.Close()
End Sub s
Private sub chkGo ld_Che ckedCh anged( sender As Object , e As EventA rgs) Handle

chkGold.CheckedChanged
If (chkGold .Checked = True) Then
lblgold.Text = "Gold is selecte d"
Else
lblgold.Text = "Gold is not selecte d"
End If
End Sub
Private Sub chkSilver_Check edCha ngedfs ender M Object , e M EventArCSI
cbtsn Handle •
ver.CheckedChanged
If (chkSilver.Checked = True) Then
lblsi!ver·Text -- "S'l . selected"
I ver Is
Else
lb!silver.Text = "S' .
Enct If Ilver Is not s elected "

End Sub
F'

- Private Sub chkBronae_CheckedChaqed(aender Aa Object, e Aa EventArgal


Handles chkBronze. CheckedCh aqed
..
emtntuml:1) ~ Qmtrols of VB.NE!

If (chkBronze.Checked = True) Then


lblbronze.Text = "Bronze is selected"
Else
lblbronze.Text = "Bronze is not selected"
End If
End Sub
End Cius
The output is as follows.

- 0

'
I
4 . 1. 7 RadioButt on Control
RadioButto ns are mutually exclusive, which means the user can select only one
choice out of a number of choices. It operates differently from the CheckBox C~trol.
While the check boxes allow the user to select one or mote items, a group of' radio
buttons allow selection of only one choice from multiple choices. It can be used for
/ ,
selecting gender of a person, marital status or any such situation where only one
option should be selected. The commonly us.e d properties and' e~nts of Radio Button
control are given in Table 4 .7 A.

Table 4.7 A: Commonly used Properties and Events of RadioButton Control

Property/M ethod/
Event Name Description I
t Pi'opertie•
-~ame ' -
This property is used in the code to identify the RadioButton.
For example, rdSwimming, rdReading.
[!ext This property is used to get or set the caption of a
I RadioButton.
'
I/
Checked This property is used to chan-ge a value to True or ~a}se
indicating whether the RadioButton 1S selected or deselected-
For ~:!t!ll11Ple, rdSwimming.Che.c ked=False
l - controls of VB.NET
~ ' -- -- -r~ ~ ~ ~~ ~~ - -__:- The AutoCh eck property of Radi 0 8 utto n control 18
· IJ set to
true, the n its checked stat e aut om atica y cha n~e s whe n the
radio but ton is selected . In case ' i·t s valu e is faJ th
d • se. e
control's value can not be checke u
smg mou se clic k .•but
only thro ugh code.
th -
It gets or sets a. value indicating wbe er a use r can gjve
the TAB key.
fabStoP focus to the RadioButton control using
Eve nts
value of the Che cke d
This eve nt is raise~ on a change in the
pro per ty of the RadioButton control.
utto n control .
This eve nt is rais ed_on clicking a RadioB
..=.:..::.:::__
~~g--:
~- ---f firin -:-ve~~ --~
--:eve
-:-ned -= :-- -= :-- ----4.-.:..
78.
_J
... lick nts is given in Tab le
C d of abo me ntio
The or er o
ioBu tton Events
Table 4.7 B: Transition Order of Rad

I Order
r- Transition
I Checked Changed, click
Unchecked to checked
tipl e gro ups of rad io but ton s are req uire d in the sam e For m, the n
- . If mul . ♦. diffiere nt set of Radio Bu tton s.
Note. ontrol should be used as con tam er ior
. .
GroupBox•t C·s a good pra ctic e to enclose the m m a con tam er eve n for a single set.
However, 1 I of pla yer
Now, design a form in VB.NET pro jec
t to acc ept a pla yer nam e, gen der
tainer of a
upB ox con trol . Cre ate ano the r con
using RadioButtons con tain ed in a Gro Silver and
me dal s the pla yer has wo n (Gold,
GroupBox having three CheckBoxes for der and
ng con cat ena ting pla yer nam e, gen
Bronze). On Submit but ton , dis pla y a stri ssa ge in
of Rad ioB utto ns for dis pla yin g me
medals won. Also create one mo re gro up
ed event. Pro jec t 4.8 sho ws the code.
Red, Green or Blue usin g Che cke dCh ang
Project 4.8: Using RadioButtons

Public Class frmSports


Ezi t.C lic. k
Private Sub btnExit_Clic.k(sender As
Ob ject , e As Eve ntA rgs ) Ha ndl es btn
Me.Close()
End Sub
Private Sub b Ob jec t, e As Eve ntA rgs ) Ha ndl es
btnSubmit.Ciick tnSubmit_C lick (sen der As

Dim displayString As Stnng.


ct·
ispJayString = "Nam 15. "
If rdFe m e & txtName.Text & "("
ale.Checked = T
dispJayStrin = . rue The n
Enct If g d1splayStrin g & "Fem ale "
a,,,,,,,onl, ~ omtrol,s of VB.NET mJ
tpu t is as follows.
Theo U

- 7
~N am e ~ ~ -

MedmlWon
Ga,1dlr FalwColorS.,.-
@ Male @ Rad
~ Gold
~Sl wr o r- - 0 ...
Q c.- ,
D Slanze

Name IS fltnav Aron,( Male) n1 has won


Gold -
Slver

_ _ PictureBox Co ntr ol e .bm p ,


418
r9_ lis U§ ed_ Jo r _djs p@ Yig gj ~a ge s of different forma ts Jjk
A PictureBox ~o.n! o~
~ Th e Sy ste m. Wi nd° :w.s.F on ns .Pi c~ eB_ox cla ss alJ
~ pg1_!p.11g , ..ico, .~ f, lt, Pi~ tur e~ ox l obJect 1s cre ate d
. It 1s
tur e!3 ~ _ ty:p e. ~y de ~u
creating an object of Pic fol der m which pro jec t is sto red
. Ma ny
to ke~ p im ~g es m t~e
always a good practice tur es. Fo r example, an image
can be
all ow dis pla yin g of pic
other controls also n's Image pro pe rty to a valid
image .
con tro l by set tin g the ~u tto
displayed on a bu tto n tur eB ox control are given in Table
4.8 .
per tie s an d ev en ts of Pic
The commonly use d pro
nts of Pic tureBox Control
Table 4.8: Pro per ties and Eve

Property/ Description
Method/ Event
Name I

Properties

[3~ e
~

Thi s pro per ty is


For example, picLogo.
use d in the
\
cod
-
e to identify the Pictur.eBox con
trol.

ault,
~ edSingle or Fixed3D. By def
BorderStyle It can be set to choices of no ne,
~
J

ture boxes are set to no ne ~ ·


- /
\ j)n{age
- Pic
d to set the pa th of the image to be di_splayed
in
This pro per ty is use
th e control. It can be set eit he r at des ign tim
e or at1 run time. For
example,
r--;.--
-
\

1-,ctureBoxl .Image = Image .Fr


.

omFile("d: \Myimage.jpg") l
ide the
y Moc1e gin g pla cem en t of an image ins
This property is use d· for ma na . following values.
' property can be set to on e of the
control · Th is
r left
► No al• It 1 ft co me r of the image at up pe
. rm · Pa ce s the up per -le
m the PictµreBox.
p

lf.J•j Common{~ usoo CotttTols of VB~

► Stretchlmage: It allows stretching of the image.


► AutoSlze: It sizes the picture box to the image.
► Centerlmage: It centers the image in the picture box.
For example,
PictureBoxl .SizeMode = PictureBoxSizeMode.Stretchlmage
ClientSize This property is used to change ·the size of the display area at ~
time. For example, PictureBoxl .ClientSize = New Size(xSize, ySize)
The following steps are carried out to set the image at design time.
(i) Drag the PictureBox Control on form
(ii) Move pointer to properties window
(iii) Select the image property of the control and Click on box having dots on right
side and a dialog box opens for selecting image file. Image can be selected
using one of the following options as shown in Figure 4.3
(a ) Local Resource: This option is used to get image from the local system.
(b) Project Resource File: This option is used to assign reference of image in
project's .resx file , which is available under 'My Project' folder of solution
with name Resource having extension .resx. This is XML file and can be
opened in any XML editor. The reference of path of image file is kept in
this file under tag <data>... </data>. If image file is removed from folder,
then the project will give error. In the resource file, a single file can be
referenced many times with different names.

Figure 4.3: Selection of Image File in PictureBox at Design Time

Resource context
0 .Local resource:

l!!lPort... Qear

@ froject resource-file:

IMy Project\Resouroes.resx
(none)
'<I I I
i'
vblo o
vblogol

VB.NET
Import...
-

~ - cm,t,of, of VB
.NET

l tirnet co n tr ol ov id es Ti m er co
.
ntrol for exec u tin g. a piece of cod e
1 . al St ud io To.ol .
box pr .
4, • al
of tim
.
e. T he Sy st em.Windows.F on ns .Tuner clas s
The V1su af te r a specified m te tv proced ur e at a fixed
us1[Y
.
ty pe . It ca n al so be us ed to st ar t a .
uo .
·
contID eai.u ~..,g db'Jiect of Ti m er •
of an im ag e or th e sp ee d of an aruman on
~ cr ea se th e SI.Ze
5 cr
dul in cr ea. se or de ba ck gr ou nd It do es no t h ave V1.SU aJ
aJloW e
. scbe:1: e,~ ~ e. T un er .Control• w• or ks m • th .
ne

nt tr ay of th e form .
Th e
1le
ti1 . ecwC i.u ~ •
pt m th e co m po
at .a sp tation at ru
n tu ne , so 1t 1s ke e given in Table 4
. g.
T im er co nt ro l ar
ti es of
represen us ed pr op er
-monlY
co1~· ents of Timer Cont
ties an d Ev
rol
Table 4.9: Proper

I
Description
Property/
r,fethod/EveDt Name 'Properties
l.
L---
e co de to id en tif y th e Timer contro
ed in th
1
This pr op er ty is us cr ea te d. Its na m e ca n be changed
i..---

B y default, ·timer
.I object is 1.
NaIIlC
e of N am e :p ro pe rty. Fo r example, tim
by ch an gi ng valu op er ty
ts .its w or k on ly af te r it s E na bl ed pr
st ar
The Timer co nt ro l Fa ls e.
ru e. B y .d ef au lt , E na bl ed pr op er ty is
Enabled .is :s et to T
al pr op er ty in
co nt ro l .allows se tt in g ln te rv
The Timer ple, if we
co nd = 10 00 m ill iseconds). Fo r exam
Inteival milliseconds (1 se se co nd s, se t th e value of
lnterval
te tv al of 2
w an t to se t an in
il li se co nd s.
pr op er ty as 20 00 m
Procedure
I

Event
of Timer control.
his ev en t is de fa ul t ev en t pr oc ed ur e
Tick / ·T
M et ho ds
Timer. Fo r exampl
e,
t th e w or ki ng of
to st ar
Start() This m et ho d is us ed
timl.start() .
Timer. Fo r example,
..._
th e w or ki ng of
to st op
Stop() This m et ho d is us ed
timl.stop(). . .
. with st ar ti ng w idth as 30
th t di y o u r ow n ch oi ce f th
Design a Fo rm
sp la ys a p1 ct ur e of co rn er o e
and startin . a · ur e in th e to p le ft
20 A t ru n ti m e, di sp la y th e pi ct
g height as te r every
W
·
lndow . Star t .
in g th
·
'd o f p ic tu re w it h a fa ct or of 10% af 'dth f
half enlarg e WI th and he ig ht . o
. second u • .
1 S .th e pi ct ur e w he n ei th er W I
ner co ntro · to p en la rg in g .
Picture becomesing Tu th . . n f p
. ic tu re be co m es gr ea
te r
gr ea te r th an or he ig ht
than th . s Form Pr . e Widtb of F or m
e height of s th e co de .
. OJect 4. 9 sh ow
ml COltmWflly 11.<e/l Control, ,
vi~~

Timer Control
Project 4.9: Enlarging Picture using

Public Clan frm.TimerPic


Dim w, h As Integer
Dim scaleW, scaleH As Double As EventArgs) Handles timePi
As Object, e c, Tic~
Private Sub timePic_Tick(sender
w = w * scaleW
I h = h * scaleH
I .
If w > Me. Si.ze.
W1'dth or h > Me.Size.Height Then

timePic. Stop()
Else
picBox.Size = New Size(w, h)
End If
End Sub
,.rmTimerPic_Load(sender As Object, e As EventArgs) Ha11dlt1
Private Sub ,i
MyBase.Load
timePic.Start()
w=30
h = 20
scaleW = 1.1
scaleH = 1.1
End Sub
End Clau ,. ..,.._,,,,,. · · · .-... .... · ·
The screenshots of output taken at different times are as follows.

~ T,nm and Picture ccntrcli Demo

oO
/RX F.'I'
00
VB.NET
VB.NET
I ',.._
4. 1.10 ProgressBar Control

I ProgressBar control is used to show visually the progress of any backgrouna


activity or the progress of a lengthy operation such as calculation of a complex result,
downloading of a large file etc. It shows a bar that fills in from left to right as the
operation progresses.

l
c;mtrttWnl~ use3 controls of VB.NET

.
Bar mo ves acc ord ing to a ran. .
ge of val ues specified bY 1·t s two pro
Progress d Min imu m. By def aul t, mm im um val ue is o
f al
•l~-.nmUnl an s def ine the ran ge o v ues to. rep res ent the
and m, .v;
~u
-
um val ue
~er
- .
ties
IS 100
pro gress of a tas k ·
,

-+;e . th ·
ue IS wn tten , it sho uld be che ck ed at the
1v1<1ft'
th propei u pro gre ss bar val
Bo ever the cod e of . val A
When e is les s tha n the ma xim um and gre ate r tha n the min imu m ue.
. d alu d 'f al . ran ge. The
s1gne v r or exc ept ion IS
e erro
.
ret um e I a v ue Is n~t de~med wit hin the
as . l are giv en m Tab le 4 .10 .
runtim d pro per ties of Pro gre ssB ar con tro
common1Y use
Bar Con trol
Table 4.10: Properties of Progress

Description
Property Name I .
~
Properties
in the code to identify the
This pro per ty is use d
Pro grs sBa r l object is
Pro gre ssB ar control. By def aul t,
~

Name
by cha ngi ng value of
cre ate d. Its nam e can be cha nge d
nam e property.
for the ran ge of valid
This pro per ty set s the lower value
it is set to 0.
Minimum val ues for Pro gre ssB ar. By def aul t,
for the ran ge of val id
This pro per ty set s the upp er val ue
it is set to 100.
Maximum val ues for Pro gre ssB ar. By def aul t,
ren t level of pro gre ss.
This pro per ty obt ain s or set s the cur
Value s for vis ual app ear anc e.
Style provides thr ee dis pla y opt ion
Style wn m blo ck
Blo cks : The Pro gre ssB ar is sho

inc rem ent s.
sho wn as a
Co nti nuous: The Pro gre ssB ar is
► mo nly use d opt ion .
con tinu ous bar. It is the mo st com
to sho w the
Ma rqu ee: The ma rqu ee sty le is use d

pro gre ss bar as alw ays moving.

tionSpeed Thi s pro per ty con tro ls the ani ma tio n spe ed of pro gre ss
MarqueeAnima sm alle r the value, the
bar. Its def aul t value is 100 . The
fas ter will be the ani ma tio n spe ed.
of the inc rem ent al ste p
Step This pro per ty pro vid es the val ue
.
wh en PerfromStep() me tho d is cal led
ject
of Pro gre ssB ar con tro l. Th e Pro
iohw, design a form tha t dem ons tra tes the use
41· s ows the code.

trol
Project 4.10: Using ProgressBar Con
Public Cl
ass progressDemo
Private s b t Object, e As EventArgs) Hanclles
btnstart.cuc: btnS art_Click (sender As
Dun.1 As Integer
c;mtfJHDffl, ~ Controls of ~
~
~
'Progexec is ProgressBar object
:Pr.ogExec.Minimum = 0
.Prog'Exec.Maximum-= 600
For i = Oio 600
'ProgExec.Value = i
Nex t
Ena Bub
End Cla n
The outp ut is as follows.

c - ·J

4 .1.11 ListB ox Control


ListB ox contro1 displays a list of items in
sorte d or unso rted order. 'Ibe
te an _ol?ject of~ type. By
System.Windows.Forms.ListBox class i_s used _to cr.ea
ber of item ~ exce eds the number
default, ListBoxl object is created. If the total num
ar~ in th_e Li~tBox control. 'Ibe
that can b ~ ~ a sc~oll b~ automatically appe
ectioJ} whic h 1s nam ed as Items
list ofi tems displayed m a L1stBox 1s also :,a!Jed ~
sand met hod s. So, Item s is a
collection~ TE.e collections are objects with prop eftie
by an inde x star ting from o. The
collection in which individual elements are referred
. The .c omm only used properties
.first item in Items collection is referred by .Items(O) '
e 4.11 .
events and methods of ListBox control are given in Tabl
ox Control
Table 4.11: Properties, Events and Methods of ListB

Prop erty / Desc ript ion


Meth od/ Event Name
Prop ertie s
,f
I
ox. It is
Name w' This prop e~ is used to chan ge the nam e of ListB
tBox·__This
convention .to use 1~t' as prefix for the nam e of aLis
control at
pro~ e~ ·of- ListBox is displayed--in the ListBox "7 /
design time. , '

Items ~ ~ i s used to rul<!/remove/clea r items to/fr orn;


~
. ow at esi ~ time or -
, using
. _pe. rties wind
is . ox rom the pro
• · - •
The step s to add items 11:
<
I vano us methods at .run .time.
~ '
coltf»lonl~ useb controls of VB.NET
ListBox from the Properties window at design time tltt 85...,
follows.
► Select the ListBox control and click in the Propenic-s
window for-selecting the ftems property for managing itenu!
in a List.
► Click the ellipses (... ) button next to the Items property to
open String Collection Editor Dialog box. where values ctm
be entered one at a line.
Properties • IX
l.ist8aw1 ¥tem.Wondows.fonnuid8or

2: El \l):, : ,.
HorizontalEmnt 0
HorizorulScrolbr false
lmeMode NoControl
Integral Height True
ltemHtight 13
Items (Celectiaa)
1B Loc.rtion 152.32

► Type an item and press enter Key.


► Click the OK button to stop adding items.
Sorted This property is used to sort items of ListBox by setting LtS
value to T.rue_:._Jts default vruue is False. For cxwnpte,
ListBoxl.Sorted = True -
Text This property gets or sea~ches for the text of the currently

·--- (
selected item in the list bo~ ~ code snippet to use Text
property is as follows.
Dim Mytext as String ' declare variable
Mytext = ListBoxl .Text 'stores selected value in variable
MessageBox.Show(Mytext) 'show value
ListBox appears empty at run time. Its Text property can be
accessed at run time only.
Selectedlndex This property returns an integer value corresponding to the
first selected item in the Listbox. The Selectedlndex value of -1
indicates that no item is selected. The Selected.Index value of 0
indicates that first item· is -selected and so on. For example,
listboxl.selectedindex=-1 'No item is selected
Selectedltem This property is similar to Selectedlndex. It returns the string
value of item instead of ind~ value. ·
. . .
For example, msg = ListBoxl.selectedltem.
Selectedltems This property_returns collection of selected items.
Count This property provides the number of items in the list. This
number is always one more than ~e · largest
possible Selectedindex value as index value_~tarts from 0.
Common{~ use3 Controls of VB ~1 '
If.JI
Sel ecti onM ode of list bo X . It
Sel ect ion Mo de Thi s pro per ty is use d to get or1 set t 1·t:m~ a t a tim. e. It may be
det erm ine s how use r can s~ ec
nde d. ., .'
non e, one , Mu ltiS itnp le, Mu ltie xte

Mu ltiCo lum n Thi s pro per ty is set to truefor dis pla yin g item s of the Ii~
l -scr oll bar also app ear s. ;
in mu ltip le .cob Jmn s. \ A hor izo· nta
-- s are di sp1ayed m · a singlef
is set \ fals e, item
to
this pro per ty
col um n and a ver tica l scro ll bar app
Me tho ds
ear s.

at run tim e. For exa rnp k


---
Thi s me tho d is use d to add an item '
Add () -
Lis tBo xl .Ite ms. Add ("S amo sa" )
Thi s me tho d rem ove s an item ~as
sed a _s arg um ent to it. F;-
Rem ove ()

Rem ove At()


exa mp le, Lis tBo x 1.It ems .Re mo
Thi s me tho d is use d to rem ove an
ve(~Sa mo sa" )
item at a sele cte d ind ex. --
cle ar the list . For exa mpl e,
Cle ar() Thi s me tho d- is use d to ~✓- ,,,.,.-,
-
Lis tBo xl .Ite ms. Cle ar()
ber of item s . .--/
-
Cou nt() Thi s me tho d pro vid es the tota l num
the Lis tBo x tha t sta rts with-
Fin dSt ring () Thi s me tho d find s the firs t item -in
- the stri ng wh ich is pas sed as an arg
um eht .

Ev ent Pro ced ure s


tBo x. It is rais ed wh en the
Se1 ecte d.In dex Cha nge d Thi s eve nt is def aul t eve nt of Lis
is -cfi: ang ed. .
Se1 ecte dln dex, pro per ty ofa Lis t bbx
is sele cte d.
Clic k Thi s eve nt is rais ed wh en a Lis t box
t acc ept s an item in a Tex tBo x, on clic kin g Add,
Now, De sig n a for m in VB .NE T tha s), removes
-an d Cle ar but ton s, add s Tex tBo x item in the Lis tBo x (lst item
Rem ove the cod e.
ect ed item and cle ars Lis tBo x res pec tive ly. Th e Pro jec t 4.1 1 sho ws
sel
Proj ect 4.11 : Usin g List Box Con trol

tBo x
Pub lic C.l au frm Ad dR em ove ltem Lis d.C lick
btn Ad d_C lick (se nde r As Ob jec t, e As Eve ntA rgs ) Ha ndl es btn Ad
Pri vat e Sub
lstl tem s.lt em s.A dd( txti tem . Tex t)
txtl tem .Tex t = ""
En d Sub
Ob jec t, e As Ev ent Ar gs) Handles
nde r As
Pri vat e Sub btn Rem ove _C lick (se
btn Rem ove .Cl ick
If Isti tem s.S ele cte din dex >= 0 The
n
) ' rem ove s usi ng sel ect ed tex t
lstl tem s.It em s.R em ove (lst ltem s.T ext
item
cte dite m) 'rem ove s usi ng sel ect ed
lsti tem s.It em s.R em ove (lst item s.S ele
sel ect ed ind ex
1stitem s.It em s.R em ove At( lsti tem s.S ele cte din dex ) 'rem ove s usi ng
End If

d
~ ,.."3 COKcro/, of VB,NBT 11D
cl 911b bt11Clear_Cllclqaender As Object, • Aa he.ntAtp ) flu4lee
io sub
.-w,t•
p•·_, at click
t,toel• . s Iterns.Clear()
15t1tern ·
,ocl sub tJllldt cliclqaender As Object, e As EventArpt Hudla ~ C l i d
ptif'te sub b -
?vfe.CioseO
Jocl sub
ocl CJ.all
J t ut screens are as follows.
The ou P - - -- - ~ - - -
-} t.ddor Remo., " ~ '""" t-:: k , · •

s.now
p., Cake
Cake
·-
AMI

[_fiiii-J [ a. ] [ 61 ldd

Now, design another Form that allows the selection of multiple food item~ from 11
L' tBox and displays them in a MessageBox. The Selectedlt ems property 1s used Wlth
,;;reach' loop control to append all selected items to displayltem s, an object of StrtnA
builder class. Project 4.12 shows the source code.
-
Stnng Collcct1on Editor , ,

--- -- ◄ l,lst8oi Tiks/, .


fnterth, strings in~ co11"6on (~ Jiff lir1'r,
DUse Data Bound Items
Samosa
UtllamtdMode Pan Cake
Cake
Edtltems...
Biscu~
Chi~

~ / .fa

11 CJnal
r Gmtm1011l~ ~ Ccnttrols of ~
Project 4 .12: M anaging M ultiple Ite ms usi ng ListBox Control
~

I
Sin
Public eta- frmLtat:Box ►
Private: Sub btnShow_Cllck(aender As Object, e As EventArp) B.andl~
,. Dr<
btnShow.Clic1L
arr
Dr
Dim displayltems As New System.Text.StringBuild er ►
do
Dim i As Integer u~
i=l The tl
For Each Item in lstFoodltem.Selectedltem s 'uses array of selected items
displayltems.Append("se lected Item: " & i & " " + Item)
Sam
displayltems.Append(Ch r( 13)) Cak
~
i =i + r
Next
MessageBox.Show(displa yltems.ToString())
End Sub·
Private Sub btnExit_Click(sender As Object, e As Even1:Args) Handlea
btnEldtClick At I
Me.Close() ListBo:
End Sub events
Bnd Class
The output is as follows.
I iiljl Food h em Select,on 0 X

iI ~,;,,,c:..
I lliocul '""
@

Oip
I
Nan
selected Item : 1 Samosa
I selected Item : z cake
II
9-
Olt

4 . 1. 12 ComboBox Control
The ComboBox control is used to display a drop-down list of various items. ListBox
I and ComboBox controls have many com ro erties which w rk:_§.i.ml-H-ftr½'.Y-""1:ef---QOth
the controls. But ComboBox is a: combination of a text box drop-down · . ext
I Box allows a user to enter anew , allows tlie u ser to select all
item from the ComboBox. Whet{ down-pointing arrow of ComboBox is clicked, a droy
1

down list of items ap'p ears. ComboBoxes are of three types-Simple, DropDown and
DropDownList.
{ use3 COKtrofs of VB.NET
a,nutton ~
'? Sil1lple: This type of ComboBox is always visible and the text portion is editable.
► propDown: This typ.e of ComboBox is expandable on the click of its down
arrow. Its text portion is-also editable_. ~
► DropDow-n tist: This type of ComboBox is also expandable on the click of its
down arr,ow. Its text porti~n is not editable. Such Com~ is read only i.e.
user cannot enter new values to ComboBox.
The three: types of ComboBox are shown as follows.

,,
r
s.nosa
vi
Cake Ii iv:
Q-ips

DropDown DropOownlllt
Simple

At design time, the Text property of ComboBox is displayed in the control, while
L" tBox displays the name property in the control. The commonly used properties,
15
ts and methods of ComboBox control are given in Table 4.12.
even
Table 4.12: Properties, Events and Methods of ComboBox Control

Property/ Method/ Description


Eve11t Name
Properties

Name This property is used to change the name of ComboBox.


The System.Windows.Forms.ComboBox class allows
creating an 01:?ject of ComboBox type. By default,
CgmboBoxl gbject is created. Its. na.iiiecru16e changed
by changing value of name· propeJ:!Y. It is· convention to
use 'cbo' as prefix in the name otaComboBox.

Items This property is used to add/remove/clea r Items to/from


a ComboBox from the prnpe.rties-window at design time
or using various methods at runtime. The steps to add
items in ComboBox window at desi gn time are as follows.
► Select the ComboBox controL-,and clic~ in the
Properties window for selecnng the Item~ property for
managingilems in a List.
► Click the ellipses (... ) button next to the Items
property to open String Collection Editor Dialog box,
where values can be· entered one at a line .
Ifill Common{~ use~ Controls f

0 ~ ''t-.h.
''1l!)
► Type an item and press enter Key.
► Click OK button to stop adding items.
Sorted Thi~ p~operty is used to sort items of ComboBo
settmg its value to True. By default its value is Fa1 :x by
Se.
Text This property is used to get/ set the text of a c0
. . mboB
After gettmg value, it can be stored in a text b , Ol(,
· some conditional lo •ox or a
· ble or can be used with
vana gic_

Selectedlndex This property returns an· integer value correspondi


the first selected item in the ComboBox. ng to
Selectedlndex value of -1 indicates that no it ~e
em is
selected. The Selectedlndex value of O indicates that fi
.
item .
is se1ected and so on. For exam lrst
1
Cboboxl.selectedlndex=-1 ' No item is selected p e,

Selectedltem This property is similar to Selectedlndex. It returns the

r Enabled
string value of an item instead of its index value.
For example, msg = CboBoxl .selectedltem.

This property makes the ComboBox read only, if its value


is set to False. For example, CboBoxl .Enabled = False
-
Count This property provides the number of items in the
ComboBox. This numbei::, is always one more than the
- -largest possible Selectedlndex value as index value starts
from zero.

SelectedText This property gets and sets the selected text in a


ComboBox only when a ComboBox has focus on it. If the
focus moves away from a ComboBox, the value of
SelectedText will be an empty string. To get current text
in a ComboBox when it does not have focus, Text
property is used.

Methods

Add() This method is used to add an item at runtime. For


example, CboBoxl.Items.add("Samosa")
-
Remove() This method remove~ the item passed as argument to
it. For example, CboBoxl .lt~ms.Remove('.:Samosa")

Clear() This method clears the list. For example,


CboBoxl .Items.clear()
~ L
con1monl~use3 Controls of VB.NET 11D

~
count()
tfing()
This method provides the total number of items.
-
This method finds the first item in the ComboBox that
matches _the specified string ~hich is passed as an
argument.
~
Event Procedure s

~ edindexChanged This event is default event of ComboBox. It is raised


when the Selectedlndex property of a ComboBox is
changed.

~ ectionChangeCommitted This event occurs when the selected item has changed
and the change appears in the ComboBox.
~

Let's design a Form that selects a food item from a ComboBox and displays it in a
MessageBox. Project 4.13 shows the code.
Project 4.13: Using ComboBox Control

pgblic Class frmCombo


Private Sub cboltems_ Selectedln dexChang ed(sender As Object, e As EventArga)
Handles cboltems.S electedlnd exChange d
MessageBox.Show(cboltems.Selectedltem & " is selected ")
End Sub
End Class
The output is as follows.

ii! Combo Box D X

/cake vj
Cake is selected

OK

Consider another example that uses a ComboBox tc store a list of food items,
ListB0x to display the selected food items, Button controls for adding selected items to
the ListBox, removing the selected Item, filling the ComboBox, sorting items, clearing
the ComboBox and displaying all items in a MessageBox. Also add a Label control that
would display the selected item and its index. The Project 4 .14 shows the code.
-The output screens are as follows .
eommonl:9 use3 Controls of VB~

alt nWor~ng with ComboB... - □-


Qioose Foociem ]
OlOOleFoodlem [ Burger


Paneer Roll
~-
L 011-· _ _~] EJ Samosas
Kachori

Selected Index and lermillle


Selected ndex cm lermame
1 Kachori
Label1

0EJEJ B
I Osplay /H ems 10

4.1.13 DateTimePicker Control


The DateTimePicker control in VB.NET allows displaying and retrievin g date and
time from the user in a specified format. It prompts the user for a date or time using a
graphical calendar with scroll buttons. The commonly used properties, events and
methods of DateTimePicker control are given in Table 4.13.

Table 4.13: Properties, Events and Methods of DateTimePicker Control

- -
Property/
Method/ Event .. Description
Name
- ~

Properties
Name This property is used to change the name of DateTirnePicker
Control.
Value This property holds the selected date and time .
. ,
.
Format This property dete~iries the format for date and time to be
displayed. The format can be selected from four predefined
formats- long, short, time and custom.
► Long format shows date in dd-month-yyyy format. For example,
21-September 20 18.
► S~ort format shows the date in format like dd-mm-yyyy.
► Tune format shows the time in hh:mm:ss format.
► .The custom format shows da t e and time
· · d
as per format spec1fie
m CustomFormat property.

.._
~n ll] use3 controls of VB.NET

custornFormat
This pro per ty is use d to dis pla y
for ma t . For exa mp le ' dd-MMM-yyyy
dat e and tirn ·
hh· mm · ed_
·
m a customized
ss 1splays d t tim. e
availabl~ fo t a ,e
-
as 21- Sep tem ber-20 18 07: 10:2. The rma s are give n m
Table 4 .14.
Ev ent
cha nge d .
This eve nt is fired wh en the dat e is
vaiueChanged
Table 4.14: Date and Time Formats

Purpose I
- f ormat
ddd
c----
The thr ee- cha rac ter abb rev iati on for
The full nam e for day-of-week.
day-of-week.
7
dddd
-h 12- hou r format.
12- hou r for ma t wh ere Single digit val ues are
pre ced ed by 0.
-- I
hh
r format.
H The one or two-digit hou r in 24- hou
pre ced ed by a 0.
24- hou r for ma t wh ere single digit val ues are
HH
m The one or two-digit min ute format.
val ues are pre ced ed by a 0.
The two -dig it min ute for ma t wh ere single digit
mm
.
M The one or two-digit mo nth num ber
ced ed
two -dig it mo nth num ber for ma t where single digit val ues are pre
MM fhe
bya 0.
mo nth .
MMM The thr ee- cha rac ter abb rev iati on for
MMMM The full nam e of mo nth .
s The one - or two-digit sec ond format.
pre ced ed by a 0.
The two -dig it sec ond for ma t wh ere single digit val ues are
ss "A").
The one -let ter A.M ./P. M. abb rev iati on (A.M. is dis pla yed as
t
"AM ").
The two -let ter A.M ./P. M. abb rev iati on (A.M. is dis pla yed as
tt
as "1") for ma t .
y The one -dig it yea r (2001 is dis pla yed
is dis pla yed as "0 l ") format.
yy The las t two dig its of the yea r (2001
"200 l ") format.
yyyY The full yea r (2001 is dis pla yed as
jec t 4.1 5
ign a For m tha t acc ept s dat e usi ng Da teT ime Pic ker con tro l. Pro
Now, des
sho the sou rce cod e.
ws
Project 4.15: Using DateTlmePicker

Public Class frmDate es


te_Va lue Ch ang ed( sen der As Object, e As EventArgs) Handl
Private Sub dtp Da
dtpDate. ValueChanged
tring())
MessageBox.Show(dtpDate.Value.ToS
End Sub
End Class
► ,
Ccmmwnl~ use3 Controls of\'!~
The out put is as follows.
0
ii Date Example

Selea Date j21-Septerrber-201812:37:43 21-09-2018 12:37:43

&ii
f 01

4.1.14 Line and Shape Controls es


Line and Sha pe controls to dra w shap
Visual Studio provides various graphical a Form
, circle, oval, rectangle and squ are on
like horizontal, vertical and diagonal line
trol s can be add ed to VB. NET For m eith er at design time or usi ng graphic~
These con Shape
ed in Sys tem .Dr awi ng namespace at run time. Line and
met hod s con tain re they
hout any han dle s and window,- therefo
controls are windowless controls wit tha t has
s are derived from bas e cla ss Sha pe
req wre less resources. These control pe object
s. Figure 4.4 shows the Line and Sha
shared properties , events and method
hierarchy.
Shape Objects
Figure 4.4: Class Hierarchy of Line and

Class: Shape

Class: SimpleShape

ult,
Line _ and Sha pe con trol s are ava ilab le in Visual Stu dio Power Pack. By defa
. The be
t udw 20~ 5 doe s not hav e pow er pac k controls. However, this pac k can
Visual S ' web site · htt ps: / /www.microsoft.com/en-
dow nlo ade d and inst alled from M'icrosofts
. c
ad( det ails .asp x?id =25 I69 . The late st ver sio n of Microsoft Visual Basi
us/ dow n1o • - d'
s are us d t O d own1oad and ms
Power Packs 1s 3.0. The following step e tall Visual Stu JO
Pac k 3.0 .
·
f ,
(i) Go to web site 'htt ps: //w ww.mi·croso t.co m/e n-u s/d ow nlo ad/ det ails .aspx?1d•
,_
251 69
• m
commonly usea Controls of VB.NET
(ii) Click on Download butto n.
(iii) Execute the file, 'VisualBasicPowerPacks3Setup.exe'
which has been
downloaded on local mach ine as a result of step ii.
chang es in your
(iv) It prom pts a messa ge "Do you want to allow this app to make
device", click on Yes butto n and then Next butto n.
(v) Check the check box with messa ge "I have check ed and
accep t the license
items" and click on Instal l butto n.
appea r. Click
(vi) After instal lation , a messa ge of successfully installed pack will
on Finish butto n.
ver, the installed
The controls available in Visual Studi o Pack will be installed. Howe
are used to add
controls will not appea r in Toolbox automatically. The following steps
them in Toolbox.
clicked on All
(i) Right click anyw here in the toolbox (here mous e is right
ry) .
Windows Form s contro ls category to includ e them under this catego
(ii) Select "Choose Items ... " as shown in Figure 4.5.
Figure 4.5: Choose Items ...

Paste Ctrl+V
~ Common Controls
~ Containers ./ List View
" Menus & TooJbars Show All
~ Pointer
Choose Items...
~ ContextMenuS
~
Sort Items Alphabetically
IE] MenuStrip
Reset Toolbox
6: StatusStrrp
TootStrip Add Tab
~

ToofStripContai Delete Tab



~ Data. Rename Tab
~ Components Move Up
~ Printing Move Down
~ D@roQ:S

Comp onent s
(i) Visual Studi o takes time to load items . Selec t .Net Frame work
tab.
(ii) Select three contr ols LineS hape, OvalS hape and Recta ngleS
hape from the list
and then click on OK Butto n as show n in Figur e 4.6.
Commonl;!J woo Contra~~ 'la
1
~
Figure 4.6: Adding Line and Shape controls

Choose Tcclbox Items · ? )(

Un~rsal Windows 8 Components Univfflil Windows Components


Windows Phone Silvertight Components WPF Components
.NET Framework Components COM ~omponents SystemActivities Components Silverlight Components
._____ _...;..__--'~'-------'---....__--=----.!.......:..:,::.:.:::_

Name• Namespace Assembly Name V,


~ DynamicHyperlink System.Web.DynamicData System.Web.DynamicData
i 4.
~ EventHandlingScope System.WorkflowActivities System.Workflow.Activities 4.
~ Hyperlink System.Web.UI.WebControls System.Web 4.
~ LineShape Microsoft.VisualBasic.PowerPacks Microsoft.VisualBasic.PowerPacks 9.
D Link System.Web.UI.MobileControls System.Web.Mobile 4.
~ LinkButton System.Web.UI.WebControls System.Web 4.
~ Linklabel System.Windows.Forms System.Windows.Forms 4.
~ LinqDataSource System.Web.UI.WebControls System.Web.Extensions 4.

Filter. lin
-Clear ]
'----- - - -- - - - - - - - - - - - - - -- - -
AccessDataSource -- - - - - - - - -
Languag~ Invariant Language (Invariant Country) I BrOWSL,J
(g
Version: 4.0.0.0

OK 11 Cancel j [ -·- 'Reset J


All the three controls, LineShape, OvalShape and RectangleShape will be added in
the toolbox under "All Windows Forms controls" category as shown in Figure 4.7.

Figure 4.7: Line and Shape controls In Toolbox

0-
•-
•- TreeView
•-
D
ij VScrollBar
~ WebBrowser , ·,i · ,
LineShape
OvatShape
RectangleShape

(i) LineShape Control


LineShape control is u sed to draw three types of line, horizontal, vertical and
diagonal. The commonly used properties, methods and events of LineShape control are
given in Table 4.15.
p
co»ottonl;t; useb Controls of ~.NET

Table 4.15: Properties, Methods and Events of LlneShape Control

--,
property/Event Description
/1\fethod Name

----
-- Properties

-- Name This property is used to assign the name to LineShape control.


I

-- aorderColor This property is used to set the color of the line.


I

1
aorderStyle This property is used to set style of the line. The style can be solid,
Dash, Dot, DashDot, DashDotDot, and Custom.
aorderWidth This property is used to set width of border of line.
-Visible This property is used to set the visibility of control (True or False).
-Xl These two properties are used to set X and Y coordinates of the Une
~ (side left)
Yl
X2 These two properties are used to set X and Y coordinates of the line
(right left)
Y2
Methods

Bring'foFront() This method is used to bring the line to front at run time.

Scale(SizeF) This method is used to resize the line. The SizeF() contains X and Y
scaling factors. For example, SizeF(2,2) will increase of the size of line
to double and SizeF(0.5,0.5) will decrease the size of line to half.
Events

Click This event is fired when the line is clicked.

(iit OvalShape Control


OvalShape control is used to draw circle or oval shaped objects. The properties of
OvalShape control, similar to LineShape control, are Name, BorderColor, BorderStyle,
BorderWidth and Visible. The Click event and commonly used methods given in case of
LineShape control are also applicable to OvalShape control. The other commonly used
properties of OvalShape control are given in Table 4.16.

Table 4.16: Properties of OvalShape Control

Property Name Description


Properties
......
Width This property is used to set width of OvalShape control.
-
Height This property is used to set height of OvaJShape control.
f ,
- BackStyle
CofflJHOH{:9 usoo Contra~ ~ ~~

This property is used to set back style of OvalShape contr


Back style can be Transparent or Opaque. The default settiti01·
. Transparent. Transparen t setting does not allow Backe R
is . olot
property t o work . The shape is filled with color on}"
J if
BackStyle property is set to Opaque.

Backgroundlmage This property is used to set the background image Of


OvalShape control.
BackgroundlmageLayout This. property se ts the background image . layout.
. Layout ""~
~1
r
be Tile, Cen t e ' Stretch, zoom or None. Tile 1s default value fo
. . til d r
. prope rty . With Tile setting,
th1s . the nnage .is e across the
.
control (repeats image). With Centre setting, ~e unage is
centered within control area. With None, the rmage is left
aligned. The Stretch setting stretches the image and the Zooni
enlarges the image.
L------ --f---=
rhis property------- -~~--:---:--::------
is used to set coordinates of upper left corner
Location
L ______ __ relative to Form.
L___ _ _ _ _ _ _ _ _ _~ - - - - : - - - - - : - ~- - - - - -

The OvalShape control is also used to draw a circle by keepmg Width and Height
properties same and oval shaped object becomes circle shaped object.

(i) RectangleShape Control


RectangleShape control is used to draw a square, rectangle, rounded square or
rounded rectangle. The properties of RectangleShape control, which are similar to
OvalShape, are Name, BorderColor, Backgroundlmage, BackgroundimageLayout,
BorderStyle, BorderWidth, Width, Height, Location and Visible. Click event and
methods listed for LineShape control are also applicable to RectangleShape control.
However, the ComerRadius property of this control is use.c tto set radius of the corners
of RectangleShape control. This control is also used to drft a square.
Now, design a Form to draw shapes. Use three CorpboBox controls to accept the
values for three base colors (RED, GREEN and BLUE). Set the background color of
rectangle, line and oval as per values entered on Click and SelectedlndexChanged
events of each Combobox. The Project 4.16 shows the code.

Project: 4.16: Using Shape Controls

Public Clau frmRectDemo


' Flag is used to check whether the control goes to SelectedlndexChanged
'Event of every ComboBox during form loading (if its value is 0)
Dim flag As Integer= O

Private Sub frmRectDemo_Load(sender As Object, e As EventArgs' eandlel


MyBaae.Load '
'Setting ComboBox with values from o to 255

em,m,,ml" M"3 Cmttro~ of~


Private Sub cmbRed_LostFocus(sender As Object, e As EventArga) If
cmbRed.LostFocus
changeColor() 'calling procedure
~,~
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnE,ut cu
Me.Close() · c~

End Sub
'This method is called on lostfocus and selectedlndexChanged events of
combobox - -· ~ eac~

Private Sub changeColor()


If flag<> 0 Then
'Color.From.Argb(Red As Integer, Green As Integer, Blue As Integer) is used to set color
rect.BackColor = Color.FromArgb(Cint(cmbRed.Text), Cint(cmbGreen.Text), ·
Clnt(cmbBlue.Text))
oval.BackColor = Color.FromArgb(Cint(cmbRed.Text), Cint(cmbGreen.Text) ,
Clnt(cmbBlue. Text))
line.BorderColor = Color.FromArgb(Cint(cmbRed.Text), Cint(cmbGreen.Text) ,
Clnt(cmbBlue.Text))
End If
End Sub
End Class - - . • ~- - .,.. a --.,..
' . ' ., ,

The output is as follows .

/I Color of Shapes - □ X

Red

Blue

I ::::::::::::)~(:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::]

m COMMON PRACTICES
The followings practices are commonly used by develo h' . . F rrns
and writing code in VB .NET. pers w 1le des1gmng o
- commonl~ MSW controls of ~.NET
(i) contin uing a long line of VB code to next line
VB interpr ets the code on one line as one stateme nt as it does not use any s pecial
symbol as statem ent termina tor. It allows a line continu ation charact er-spac e and an
underscore followed by enter key. This will treat the next line as continu ation of the
previous line. However, this charac ter cannot be used to split literals , identifiers or
property names.

(ii) Locking contro ls on a Form


After placing all control s at the desired position, developer can lock them. Right
-
click the mouse on empty area of the form and select lock controls from the context
menu.

(iii) Giving Remar ks/Com ments


Good docum entatio n is must to increas e readability and for better mainte nance of
the code. VB.NET allows to add remark s by starting a line with single quote ('). The
Comment lines tum green and are ignored during program execution.
► Multiple lines can be comme nted using the following

• Select lines of code


• Press Ctrl+K and Press Ctrl +C to make those lines as comme nt lines.
► Multiple lines can be uncom mented using the following
• Select lines of code
• Press Ctrl +Kand press Ctrl +U to uncom ment the selecte d lines.
However, VB.NET allows doing the same with toolbar options.

(iv) Changing Multiple properties of a control with With .. .End With


Several propert ies of a control can be change d easily using With .. .End With
statement. Statem ents written with in 'With ... End With' are said to be within block
on
statements. Such statem ents are said to be more efficient as they take lesser executi
time.
Textboxl.ForeColor = Color.ForestGreen
Textboxl.BackColor = Color.Cyan
Textboxl.Text="Demo of With ... End With"
Above statements can be written as follows:
With Textboxl
.ForeColor = Color.ForestGreen
.BackColor = Color. Cyan
.Text="Demo of With .. End With"
End With

You might also like