You are on page 1of 24

Chapfor5

Quic~ Q.e\ 1se


QI l ,pt,un lhl' Contn,t dJ,, .
\ lb: l.c tro d.1_,,, l'- ,m t,.1,l' d,1,, Ill! .1II \\1t1dlm ... I l,rn1, controls. It tmp_l~ments basic functio . '
h ._ h.mJ ~ u,u m1'ut lhrl,u~h 1,., ., bl1,ud .rnd tnl)ll',L' and dl'ftning pos 1t1on und size of a con,nahlies,
t 11 ,,u,l'\..J h thL• l 1,1......'-'... th.,t d1,pI,,, mlL,1 mJl1on to the user. The Control class is ~0 nent
• .._,n"
t.."w n.,\\ m,i "" , 1·L•rm, n.m,l''-1'•, ll
.. n.'11\ .• • paced
1 tnsid,

\\ hi,h ml.'lhoJ 1, u,l'd to gcnl'rJlc the die\... c\'Cnl of the Control class for a Button control?
lb.: Button l .,..... h,1, ,l rcrh,rmlltcl,., ml'lhod _ used to . ~cnerate the Click event of lhe
' \ ,t1.:m.\\ md,m , form, ll,ntrol d.1" The PerlormClic\... 111l' thod 1s mvoked for buttonl as follows:
~ttonl. i:>erfnno<l, Ckl)
\\'h.at i, lhL' Ri1.:hTc,t80, control?

The Riehl o..:.\:13,,, 1..onlrL,I ,~ u,L•d IL,r d1,pl,:n mg, l'ntenng, und manip~lating rich text with fonnatting.
L', unuar to tlw f1..•,1&,, n,ntrol but 1111..'1~ You mul-.c the Lc,L of a R1chTe,LBo\. con trol bold, italic, and11
undcrlmed ch,,n~e the c,,IL,r ol the te,t ,cI..xt font design «nd font si.les. You can save the text of a
R1JtlextBo, uintrc.,I tl, ., nch i..-,t ILlrmJI (RlT) file, and load the tc,t of a RTF file in a RichTexlBo~
ninttnl

Q-4. C:in \\e di,plJ) an image or icon on a Button control?


Ans. Lo: tnn 1.. J,-. Clm,1,1 the lmJge properl\ which is used to set an image on the Button control. You can
al<-0 :,ct th1..• .1hsnmi.:nt ol thi.: image b, u,ing the lmageAlign prope rty of the Button class.
Q5 \\'hat 1, the u:--e ol Pa-.,wordChar property?
Ans. The Pa,,,~ ardChar rropert, 1s u-,ed to set the password character to mask original c haracters entered by
us.er:--

Qb. HO\\ can , ou auto size a button to fit its text?


Atb The Butt • ..ontrol has the Aut0S1t.e propert,,, ,, hich ca n be set to true o r false. If we set the value of the
A
ut ...,,ze proper!) to true, th1:n lhe button control au to matically alters its s ize accord .mg t0 the content
d1c,pla, ,:,:I ~ it.

Q,. \\'hat are the three states set in a CheckState property of Check box?
Ans n.. three ~l.111..., ut the Ch1.-ckState property are:
.J Ch1.d 1.-d
.J Uncht-ck1.•d
J lndt:te rminalt:
Q8.
\\'h,1t is the difference between the Add() and Insert() methods of a ListBox control? . at the
J\n<;
rt. ,,,,,c..J mdl X
H,, , \d<lO ml'lhc,d ,impl) adds an item into the list box, whereas the Insert() method insert an item
Q9
\\'hat 1s th e difference between a ListBox co tr I d C b B tr J? B .,
n o an a om o ox con o . C mbo o
\ nu _Jn nnl.., m i~e a ~·li:ct1on from a li<.l of items from ListBox control, whereas with a o
cnntrol lhl u tr dn mc1k ... c1 't·lec11on from th 1. ·t f . II k · own e ntry .
QlO. ... 1s o items as we as can ma e I1s
What doe!> the D ialogRe'>ult property of tt j,
An.,. 8
1 Ill D11\ 1gl<L...,ult k'"~rt ntn, ,.l..., c _a u on control . do? f when the button ·
c Ill 1cM 'CI• lh 1s proper1\' 1~
• U<;t·J
' ""l: . ,
1
lo ,r..., .. d . a va
1
bo1ue that 1s returned to the parent orn1
, <-u " la 1CJ~ XC<;,

214
Windows Forms
Controls - II
If you need an Information on: See page:

Defining the RadioButton Control;,-- 216

Describ1ng the CheckBox Control .,,, 220


Exploring the List View Control 224
Defining the TreeView Control 231

Describing the Panel Control, 236


Exploring the GroupBox ContrgL 240
~aining the Tab Control Control 242
Chap 6
l . n L' ll•,u,w,i ,,l,•ul ,,,nw, L,mnH,nl\ ll"l.'d s ta ndard \-Vind
', '• f ,u
fl•, tB{'' ,,nd:,. t.,,l...,·,,J l l' \.I B
, L''L ,.,t Bo,, C l
1cckcd ListBox owsdFo~
t I lx l c,t ' ' ' ' •
...,s contrOI
I \\ md,'" ' J\ ,m,, ,l.,nlrl,I., -;ul 11 "" Rad10 Button Check'Ban Co ho
rn Bo)( ·,~ sUch
_1 '-•
r:a ~,,Th,
., .1 t lnbt ontnil ,,,nt, ,,1, I hl'''' n1ntroI., r0t ml I1c ILM.,1c
"'' . • , ox, Listv· Co"ltot
l r~ , an, th th• J}'l'li,, ,t 1,,n l hL• u 1ntn1b th,,t \ 0u Ic.1rn m .
lavout of an a .
PP1ICatio h l'r~"
•ew, ....y u
.... p ih1 \\I lh1s c hapter can be . n l at llSe ieiy·
t.: h 11
"' tlll I r-l cJll):,'1 ' 111.:fod,·, thl' u1ntn1I, l ,1t ., ~'" ',·ou lo d1spl.a . d1vid d tscan
y items (value s: e_ "'_to I~
lh: ~,l,ml LJl,~i•n· md udL'' th,• , (,nt11,l, th,,t pn,, tL"h: \ ou lo sclecl1 on
option to the ~seListV,ew and
l'hi lhu~\ c.itl"·,, n md ud,·, thL' cl1nLH1I., thc1l arc used lo group other
\ ·c- contr . r from two
'1 1abl: n 1 l o 1s. GroupB or
ox, Pall\'I,
h::rtc, \QU IC'~m .,lx1Jt th, 1mpk'nH•nt.:1L1,,n nl these rnntro b, in
'' a \Vindo ws Forms a . .
... tt, he r H'U J,'\:id,• "lm:h u111lrnl ln use . :t • 1,canon.
•"'' lor " 11al pu1.pose • .
a nd g ive you an idea of The ba11c
PP
-onh u~ rropert1,...., m,:tlw d ..... .1nd c, L'nh ol LhC'-L' contro ls.
the lllo1t
rt, nm, "P'n"' th~ C\, ntn1I, m dcla1b.

De1ning the RadioButton Controls


_ .. \. ..,1n1I .,l,o \...no,, n ,1.., an l)pl1on bullon , ,~ us~d to select
a n option from a set of options. (The
RA.i: B.attnn L-- 51muar 1(1 the '-hl"Cl... bl" but there ,~ one mam d,fference
. A ch eck box can work independent!
,, herro.s rJLHO bulllm ' ah, a\.., wor\... m groups .) 'I ou can only sele ct
o n e optio n from a group of radio butto~
t =.u-c,l It mean., that,, hln,•, l'r you select a radio button
from a group of radio button s, the other radio buttons
~ the sroup are ,1utomJ ttcJI\\ dl',clec ted In contra. ,l,
) ou can select a n y numb er of check boxes from a list of
Jit.-n bo,e-, ln othl!r word, radio butlom. arc used for single- select cho ices, where as check boxes are used for
rr~'tip '~le<t opti(1n, 'I ou c,,n u:,e the Checke d proper ty lo get
or set the s tate of a radio button. You cap
d -r!.n ll.').t, an im.1g( or b(llh on Radio Button control . Moreo \'er,
the appea rance of a radio button may be
lllter'ro <;o th.at tl Jppear... ~ a toggle- style button or standa rd radio button
by setting the Appea rance pro~rty.lf
\ mi \\"a.."ll to pl.11:e more than one group of radio
button s on the sam e form, you must place them in different
con!a:ncr contrnl, c;uch as GroupBo, or Panel. Fo r examp le, vou h ave · button s w,t· h their text
fo ur radio
properne:: ~, I Smgle ~lamed , ~1ale, and Female. Now, when -u sers try to d"
10 bu ttons thev
select any two ra ' th~
will 00~ be ar·.e t. do '-O because thev can select only one radio button
a t a time from the set. To enable
<,,clei..-non o! multipl ,· radio buttoru., the radio buttons ~us t be
grou ped into differe nt contai ner controls. _
llleo . .1 10o
~ 0-ut:on control is created b) using the RadioB utton class. The hierar Rd'10 Buttonclass 1sas
folio\\£ chy of the a
Syste::i .Object
Syst~.M arshalB yRefob j ect
5Yst eM.COMponentMode1 .compo nent
System.windows.For ms.con trol
System .Windo ws.For ms.But tonBas e
Ta hie 6 l l,c •c n~•..... _ System .Windo ws. Forms . Radi oButto n
rlh, properlles of the RadioButton class:
Table 6.1 Noteworthy Properties of the Rad' B
Property 10 utton Class
Descrtptlon
(<ldiO
Retne\ec;
button.
or St-ls lht• , I r - ~ -- - . ·- the appeara nee of a
a uc or lhe App,.a rance properl y thal d e terrrnne s id
Rt-tnt'\e ,, or St-u av I
aulomatJcal)v 1..
R
. d
a uc m icalmg whethe r the Checke
, C, wnic when "O 1· k
-
d va lue a nd the appea ranee of
, u c tc anywhe re on the rad,o button.
a control snou

( a o ,c
~ "~
l
-on ~islS O • i an,l
etneves or ~ts lht.· loc-aticn 0 r h
oo, I
port10n anti
U1e Cllptmn I\ u=d
propvrlv , th,• J'<Xihon

.,,_ lo !-el
' t c chl'Ck box portio n o f a radio bu tto n . A ra dio button
a G.iplmn. The• ch I- be
.i htlt
I '(

on
o1 l1,,, ch, ~ ......
I
h
.
,x portion delcrm ines 1f the ra 10 d " button
l' radm bulto n \o\' hen you ..e t a ra ,o i,,ne
15 s
<.
. ·elcdcd or
• er•.
d " bu ll Oll.,
d to
c1e,1rcc n

thl'
·
1;.P.. ,~
pri-'re r11
· l
w lul c the.- 1e:.1 rl'fna ' V<J)( portion c hange!> a ccordin g to 1 ", valueti a s" a
in~ unch.ingl·tl ' ...,.-1
;,, ~ '.
l<l'lnt"\ e-. ~ r !14:l'> a\ I - - - -~
Ju,, ind1,.i1in . h I
Kt'lnt..''\
c •~ or ~•b lhl' Cdfllu I
g w l'l w r ,, r.id1U bullo n •~ ,;;c lec lclI.
If\ tor ,1 radu, hu1t11n

216
-----
p,ope
rty
. Noteworthy Properties of the -RadioButton Class
Table 6. 1 . -
Deacrlptlon
- Retrieves or sets a va Iue m . w h eth er a user can give
. d'icating
-~
Windows Forms Controls - II

~~
~
~

. focus to the Rad10B•JC :.en controI b Y u-:ang


st0
rab P the TAB key.

·oButto n class has one public method, PerformClick, which generates a Click event when a user selects a
The Rad 1
radio button. .
6 2 lists noteworthy events of the Rad10Button_class:
_
TabeI •
Table 6.2: Noteworthy Events of~ RadioBu_!ton ~ s - ~- ~ -~ - ~ ~ - - - - - ~ -~ -- - - ~
Event
AppearanceCh a ~
- I- Description
Occurs when the value of the ~~r~ce property of a Ra ~u t.~~n_c~~I chang~
~Chec kedChanged Occurs when the value of the Checked property of a RadioBuuon control changes

Let's create a Windows application named RadioButtonSampl e (also available in the CD-ROM) to learn how can
you use the various properties and events of radio button control in your application. In this applicallon, three
radio buttons and one Button control is added in Forml. The radio button controls are horizontally placed in the
Forrn1 and when you select one of the radio button controls the Button controls align accordingly to the selected
radio button control. Perform the following steps to create the RadioButtonSampl e application.
1. Set the text for the RadioButton controls
2. Retrieve and set the check state of the RadioButton controls
3. Create toggle buttons
Let's now perform these steps one by one.

Setting the Text for the RadioButton Controls


You can set the text of the RadioButton controls either at des ign time or al run time. Al design time, you can set
the Text property for the radio button by Properties window. However, we explain how to set the text of radio
buttons at run time. Perform the following steps to change the text of radio button at runtime:
1· Drag and drop a Button control and three RadioButton controls from the Toolbox to the Form L.
2
· Set the Text prope rty of Forml to Radio Button Sample and Buttonl to Click Me.
3
· Ad_d the following code snippet to the Forml's Load event, as shown in following code snippet:
~r,vdate Sub Forml_Load(ByVal sender As system.Object, syval e As system.EventArgs )
an 1es MyBase.Load
Radi oButtonl. Text = "Left"
RadioButton2.Te xt = "center"
RadioButton3.Te xt = "Right"
End Sub
4
· Set the font style for all the radio buttons as bold.
S. Press the FS key to run the application. The output as shown in Figure 6.1:

~ ... l

Figure 6.1: Setting the Caption for Radio Buttons

217
na ana Settrng the a1ec.( State of the Rad10Button Controls
t I' l uth,n , .. ,dl"\.ll'\I ll\ u ,nb lhl ( lwl "l'd l'l'l'Pl'rl\ 1lw C hl'dwd pr
11 ... I nil' ,1 tlw hullt'" '" -.l•h~l\'d .md 1:.,1 ...l' 11 it I'- nn t '-L'k '( IL' d . 0 Pert, or

RJ,lr\1Bu1tnt\.....,,_1mpll•, to dl·1111,n,t1,1h.' "Ill tlwr ,1 1,1d10 b uLLon 15 'il'lcct d


e . Perforrn
k \k button ,ll dl,1g11 t111w ,111d ,hid lhl ll,llll\\'i ng t nd,• '-111 l'Pl' l, ,,._ A•vcn in L
,,t ,\ R.1dn1 l\11th,11
•tilt·(. hi., k '-t 11\' isting b I:
'"' th,t.tonLcl,cl..(B)\cl1 send,•1 As ::i\<;tem ObJect,
~tt 1.Chtl Byval e As System.EventArgs)
l • iao,o uttonl.Chl'cked .. 1 rue l hl'n
M'-gSOx("Ttle Rad10 Button Left 1s selected")
£ s~i~ R.ldloButton2.Checked • True lhen
i.1sgs0:..( The Radio Button Ct' ntl'r is selected")
t'seif R•diosutton3.Chec~ed • lruc Then

~~oBox("lhe Radio Button Right ,., selected")


l~ If
t_nd Su!>

the l ~ "'-" lo run the R,1d1,,l\utt,m....,ampll• ,1pplk,1 111111 \\ lll'n tlw f,irm ,1pp e,1rc;, ob ..e rve thal the first
lt Ldt ,.., --cll'Cll~ b, ,h-1,llllt
I.. th.. l.l \.k \IL• bu11on .1 mr-."-lgl' hl,, ,, d1,pl,l\ '-'d, "h1ch indicah.'-; lhil t t he Left rndio button is selected,
~ n in I asun.: C,.::.

Ct ~ il

• I.on

RaoollunonS..mpl.,

The ~d,o Button ltf1 tS ••l•ct~

OK
'-
Fi gure 6 2· Displaying a Message Box on the Clicking of the Button . ,
) l'U c.in JI«.<> !>Ct the t he:d . I ,1 J r.1d1n bullon '-l'll."ded, espec1all} in s uch cases w he re yo u h ave to d1spla)
d.11,1 Jrom till' dJt.ibas.:• on a radio button l..:t'-. mo,·e lo the next s tep to perform th1s task .
th
•t Add l" lnllo,-. mg lughhghtcd code sni rpe1, ac; bri, t n in Listing 6.2, 1n the Load event of the fo rm:
l j , 1j ng 6,2: S.•I ting lht• ChL,:-l. St.,')t,• of R.-:id 10 Bu lion._
Privatt> Sub Fonnl.J.oad(Byval sender As Sys t em . ObJ·e c t , Byval e As System.EventArgs) Handles
MyBase.toad
RadioButtonl.Tc•t • "Left"
Radioeut~on2.Te~t • "center"
Rad10Button3 , Te~t • "Right"
Radio8utton2.Chec ► ed • True
end Sub • ,,·n
c; Pre--, th1..· I 5 k,•v to l~•!Cuh• tlw :ippl1cdttr,n ·1he form "PPear-, w ith thl' '>e lecti o n o f Rad io Bu 110 112, a~ ~,10
Ill f1gur.• f, ' •

218
Windows Forms Controls - II

...,,,

Figure 6.3: Displaying a Selected Radio Button

creating Toggle Buttons


) ou can turn radi o buttons into toggle buttons to give them a button-like appearance. You need to ~et the
Appearil nce p ro perty o f radio button control to Button (by default, the value of lhe Appearance propert\ is
Normal). Toggle butto ns resemble standard buttons but ac t similar to check bo\.es or radio buttons.
Let's now learn ho w to tra ns form radio buttons into toggle buttons in the RadioButtonSample appl11:at1on
Perform the following s te ps to do this:
1. Add the fo llo wing highlig hted code snippet, as shown in Listing 6.3, in the Click event of the Clicl-. l\\e
button:
Listing 6.3: Showing the Code to Create Toggle Buttons
Pri vate Sub Buttonl_Click(Byval sender As System.object, ByVal e As System.EventArgs)
Handles Buttonl.Click
If RadioButtonl.Checked = True Then
MsgBox("The Radio Button Left is Selected")
Elseif RadioButton2.Checked = True Then
MsgBox("The Radio Button center is selected")
Elseif RadioButton3.Checked = True Then
MsgBox("The Radio Button Right is Selected")
End If
RadioButtonl.Appearance = Appearance.Button
RadioButton2.Appearance = Appearance.Button
End Sub
RadioButton3.Appearance = Appearance.Button
2
' ~ dd_the following cod e snippe t, as sh own in Lis ting 6.-l, to the Checked C hanged event of the radio button'>
align the Click Me button to the left, ce nte r, or rig ht edges of the form, as pe r the radio button .,dtc•ckJ b,
ti1e user:
listing 6 4. . .
P . • • Aligning the Click M e Button on the Selection of a Radio Button
r1vate s u b RadioButtonl_Checkedchan ged(ByVal sender As system.object, syval e As
syst
em.EventArgs) Handles RadioButtonl.Checkedchan ged
End Sub Buttonl.Location = New Point(S, 100)
Syst:;ivate Sub RadioButton2_checkedchan ged(ByVal sender As System.object. ByVal e As
-EventArgs) Handles RadioButton2.Checkedchan ged
Buttonl.Location = New Point ( ll0, 100)
Ed
n Sub
Syst:;ivate Sub RadioButton3_Checkedcha nged ( Byval sender As system .object, syval e As
-EventArgs) Handles RadioButton3.checkedChan ged
Buttonl.Location = New Point ( 23S, 100)
3. Ed
n Sub
Press lh F the Rihht r.1d1,1 buttl,n ,ind
ob e 5 k.ey to e, ecule thl' appliLa ti o n \\ hl'n lhl' t0rrn appears , :-L·IL•.: t -
'
serve II1 a t th e butto n jr., a ligned to the right, a-;'- I1l)\\ n .in r1g-ure 6.~:

219
ldl

1
, t he R'ght
Figure 6.4 Selecting •
Radio Button• to •Align the Button to the• Right
'
lh" a · k ~k butllin.. ll11:"'-<1b'-
't 0
\
- . lmg 5
. lhe6 selec e
. : ted radio button, and then all th
I
l'i displayed md1ca
r .. ,
a I.: i\ i I) I wglebo,
\
,
buttons,
,
as shown Ill Figure
~ ------_-:._~-=:
.ldm button_, .11'\.' lnru.t0rmn L·.=_l~:--~ -;.
:::--i=.;=...-f,!~~-,
'- .
......,,.. ..... ~.~ ~c:;,, s ,sa..

'
I.all Gort.,
I

11

'

Figure 6.5: Radio Buttons Transformed to Toggle Buttons

Describing the CheckBox Control kB control acceptseil der


7, 1,., .Bo, control m,tes, check ho, that can be selected by cl ,c mg ' ·
. k' it. ·tWThe
elect a check ox, it holh s
h ee ox
Cyou b
True or Fabe , alue. \ ou need to clid, a check box to select o r d eselect h en th
5
the ,·alue True •nd when vou clea, the check box, it holds False. check box • ,..

A Check&, control h,s th,ec st•tes, checked, unchecked and m . d eten run , unkno~
. a te ·. When a "e b ·id,in;o",e
I ctionn
ondetemun.te ,t.i,, n is g«yed-out. AppHcaHons use this state only when a pa,tta 1 0t xt box is edhe< ; , ;i,I<
to h, '"P<e<ented. Fo, "'ample, \'Ou can use acheck box to detennine if the text ,_n a if\ h e text is in bo te0 ,r "'
1
o, a rnmlnnation ot both Now. using the check box, you can very e~sHy d ete rrru;;e o ut the cu'."nt ::rected •
" "''"'"• " ·hen th, le>t • both in bold and in italk, ;1 becomes d ifficul t to hg_ that is, e,ther '"'bl• '"

dc'Se ''"=
.. ..J c; uc h a stat, "hen, the selection ~
chec,I be- sonce, by default, the check box can display only o ne state a t • tim e, . ate state. To d ,o "'
unknown ;s known as t h e m k boxes a,e base
· d e te rmtn
indetenn.n.a1., ~late, ~t the Thr~tate property of the check box to T ru e . Chee
Chl-cl-.Box cla-,, The hierarchv of the CheckBox class is as follows:
Syste11.0bject
system.MarshalByRefobject
5t
Sy ~.CoaiponentModel . component
t
SyS em.w 1 ndows. Forms.control
System .windows. Forms.Buttonsase
class: .Forms.CheckBox
Syst em.Windows
Tc1ble 6 3 lisb noti:wo rth\' prop.•rtit..., of the ChcckBox
Table 6.3: Noteworthy Properties of the CheckBox Class

o........., - - ,,,,,
➔---..:....:..r.51: ;·,: ,_
..._,ty Rc1r11!Veso t h - - - ,nee
A~~lll'.'an-e

~
1-....:..::__ _ _ _ _ _ _ \ I P dPr,·.:irancc of a chl><:k box appear, ------
ofJ
•• • • pc,"" S ·, wh,lh,-, "'""llhe k, ' o, h• r > -" ,e va Iue and dlhe ...---
220 ---------- -i-____ bo" ~hould Lie 1
a ::.:.:.:,om::;:4t
.;..:_u lly?:.~ch~angcd whl>n the ch~c k box is select~
1.r.:!.i~
::,:
Windo ws Forms Contro ls - II

~ . Notew o
rthY Prope rties of the-Check Bo~ Class -
_
3 De■cr lptJon
fable 6·
proper1Y
·
~~--r
cnecltAl i•Jn ___ __
Retriev es or sets the horiz o~ an~ ~~li~~t of
the check mark on a check box
Retrie-;es or sets a va~e indi~ti n.2. wheth er or~ a ch_eck
box ts in lhe :,ele-:ted slate

checked --- Retriev es or sets the s tate of a check box


- · f _
h _ k_bo _
t ate I Retriev es or sets the captio n or a c ec x
CheckS
--- ---- Retriev es or sets a value indica ting wheth er or not a check
box should allow thrl.>e check

1 states, rather than two ____ - - - - - - - - - - - - - ~ ~

,! lists notew orthy event s of the CheckBox class:


Tabe 6· -
[ . Notew orthy Event s of the Check Box Class
Table 6·4 ·
Even
t _
Description -
Occur s when the Appea rance proper ty of a check box has
---
change d
Appea ranceC hanged
has change d
Occur s when the Check ed proper ty valu~ chec k box
CheckedChanged

..
- -

-
CheckSta teCha nged Occur s when the Check State proper ty value of a c~k ~has
change d
- -
A CheckBox control can displa y an image , the text
associ ated with the check box, or both simul taneou sly. U!>e
on where the image and captio n shoul d appea r
the lmageAlign and TextA lign prope rties to determ ine the locati
in the Check Box contro l. You can also use the lmage
List and Image lndex prope rties of a check bo, to displa y an
image on the check box.
name d Check BoxSa mple (also available in the
To know how these prope rties work, let's create an applic ation
Box Samp le. This applic ation displays the total
CD-ROM) and set the Text prope rty of the Form l to Check
ts of a TextBox contro l, a Button control, a Label
number of words and chara cters entere d in a text box. It consis
the functi ons of the CheckBox controls:
control and three CheckBox contro ls. The follow ing is a list of
of chara cters entere d in the text box
0
The first CheckBox contro l, Check Boxl, count s the numb er
O The second Check Box contro l, CheckBox2, count
s the word s entere d in the text box
te state
The third CheckBox contro l, CheckBox3, is set to an indete rmina
0
on wheth er or not the Check Boxl and CheckBox2
The check state of the Check Box3 contro l is determ ined based l
contra1s are 1 t d If are cleare d, then the third CheckBox contro
als . se ec e • the first and the secon d Check box contro ls . . 1
h c· third CheckBox contro l 1s a so
o rematns cleare d·
selected .' 1"f t e 1rst two Check Box contro ls are select ed, then the
the other is cleare d, the third CheckBox control
show 5 · ~owe ver, if one Check Box contro l is select ed and
·
an indete rll_lma l displays the total numb er of
charact te s tate. The Label contro l used in the applic ation contro b d
ers and word s en tered m . the text box when a user select s the Check Boxl and CheckBox2 check o,es an
clicks th p·
p e md button .
erform the foll .
1. Se owmg s teps to create the Check BoxS ample applic ation:
t the text f h
2. R . or t e Check Box contro ls
ls
3. /triev e and set the check state of the Check Box contro
reate the thr
let's ee-sta te Check Box contro ls
now leam ho
Sett,· w to perfo rm these s teps one by one.
tng the Ti.
Silllilar t ext for the CheckBox Controls J T I Tl}'
Perf0 rrn otheany othe w· d for a check box b) u-;mg t ,e ex prnpe ·
follow ·r m ows Form s contro ls, you can set the text
l. Dr mg steps to set the text of check box contro l: f 1 1 n • add a
Jl.n·o
ag and op a T extBo x contro l to the form and set its Multi line prope rty to True.
dr n a
Butt0 .
i n contro l tO th e form and set its text as Find.
Adct thr nd
and CheckBox3) to the Forml a Set lheir Text
Ptope rt/~ Check Box contr ols (Chec kBoxl , Check 8ox2,
code snippe t:
m th e Load event of the form, as s hown in the follow ing

221
rr As \)\ t ~m.ObJ~ct, O\Val e As Sys tem.(ventA
rgs)
S lOUnt '
11. d\ couril"
thcd box d1s pl ,w1n9 indl't e rminat: l' sta te "

l h•m, ,md ,d llw h·,1 p1,1p,•1l\ l11 llw ,1111 11 n l ln bl,111k


ilu • ll'- I n 1hll'\i pt op,•t I\ lo r.11 . . ,, In ,1dJ1t1nn I
, l t,abll' the

l ' \ ' Ill tin: .1pplt,,,t11111 1lw f, 1m •'l'I'•'•" ' ,,, , hnwn in Figtlf l' 6.<i:
1

O,.,eut

Figure 6 6 Displaying Text for Check Boxes

Retrie\ ng and Sett1ng the Chee/.. State of the CheckBox Controls


" r ,, dh,I.. !'''' 1, ,l'ln ll•J b, u,mg ib Ched.cd prope rty. This properly can be
Tru or F.:il~ TI,e <.tall' 111 tlw ch1..'CI.. bo'I: c,111 ,11,o be determined by setting U,e control's Checked
T
rt:( l r hl-.c Ld., u...., th.:> ,,,ml' .i pphc.1lllln
. . C.hed
. ,Bo'5ample, to show
· I.f a ch ec k box 1·s selected or
lt-: f , mg o;teps to d,i tlm: r

, . the Find button at dl-...1p1 timl' and add the follow mg code snip pet, as s h o wn 111
"' · Listing 6.:1, in
.od "' m.do\\
L1st1ng 6..5· Rctnt: g the Che.:I.. ~l.\le of llw ClwckBl)\ Control..
Pri~~le S(;!> Button1_Click( Byval sende r As system. object , ByVal e As system.EventArgs)
H.l..~le~ E- ttonl.cl,ck
If Check.e.oxl. Checked = True And Checksox2.Checked = True Then
Checke.o, 3.cnecked = True
Else!f Check e.o, l.Chec~ed = Fal se And che cksox2.Checked = False Then
Checle-0• 3.Check ed ~ False
El\.d If
rnd Sub
th 11 1 ,n
\ddI L•d R , t of
tht:
.. tughlightc.cf codi: sn1rp,·t, a,; ~h n wn in Listing 6.6,
'"~the form lo set the check Sla te of Check Box
I ,._ting 6.6: C.C.:ttms; th<> ( hed Stat, of a Check fiox

Svb ron::.1_.LoadreY"Jal SPndPr


PrivatP "','Base.Load
t1.indl.-s - As Syscem.ObJ·ect, syval e As System.EventA rgs)
Checkeo:d Te •t • "c.ha r s toun t"
Checl.:Ro;or: 2. Te , :.. "•ords count "
CheckBod.Ten
CheclBO•l • True bo,. dis pl dying
• "CJ-eek
Ct:\.ec.~ta · i ndeterm,· nate state"
Text80)(J .Text • w-lt()!IJI! t
0
Label 1. Te.xt ., .. Toul , NET 4;,o Programming"
[nd ~ub charactt rs : & Texteoxl.TextLength
PJTC th~ J , i l \ IO t•• l'CUI(' tlw a ppliuit1, I rI 7
1
n h• f ,r111 "l'J>••.irs a, , hown in I 1)-; Ltrl' 6. :

222
Windows Forms Controls - II

,, O...o:u1 --- ---- I


ac, Fii use;_._._._
'

["r..1 J
r,..1 - . , 3 1

Figure 6.7: Displayi ng a Selected Check Box

creating Three-State CheckBox Controls ed. However, to display


,~~lclll'd earlier, a check box typically displays two states, that is, Checked or Uncheck
True and the Chec.kState
lhl' indcll'rm111ale slate, the ThreeState property of the check box should be set to
property to ChcckSlale.lndetermina te at design time or run time.
Perform the following steps to create three-state CheckBox controls:
1. Add the following highligh ted code snippet, as shown in Listing 6.7,
to set the indeterminate state of
CheckBox3 at the Click event of the Find button:
Listing 6.7: Setting the Indeterm inate State for CheckBox3
ventArgs)
Private sub ButtonLClick(ByVal sender As system .object , syval e As system.E
Handl es Buttonl .Click
If CheckBoxl.Checked = True And CheckBox2 .Checked = True Then
CheckBox3 . checked = True
El ser f checkBoxl .checked = False And checkBox2.Checked = False Then
checkBo x3. Checked = False
Else
CheckBox3.ChecRState = Chec'iSta..te.~detenrinat•
End If
End Sub
2 Find button to display the
· Add the following code snippet, as given in Listing 6.8, in the Click event of the
. . total number of characters and words entered in a text box:
Box .
LiSling_G.S: Displaying the Total Number of Characters and Words Entered in a Text
7 .
Private Sub But tonLc 1ck(Byval sender As system .object , ayval e As s ystem . EventArgs)
Handl
es Button l.Click
Dim wrdcount, chrcount As Integer
Labe11. Text-;. '"'
Checksox).cnecked = False
If Checkaoxl..Cflecked = True Tt;en
chrcount = Textaoxl.Text.Length
Labell. Text = "Total characters : " & chrcount
End It
If Checksox2.Checked = True Then
If Textaoxl.Text.Trim.Length = O Then
Labe11. Text = Lal>e71 . Text & " " & ''Tot al worcls • O"
else
Pim strO As stri ng = Textaoxl.Text.S plitC: '1
wrijcoont = str. Length
latiell. Text = Lal>ell. Text &" ...-& "Total worfJs
End Ii\
End If
If Checkso xl .checked = True And checkBox2 .Checked = True Then
Chec ksox3. checked = True
El serf checkaoxl.chec ked = ralse And checkaox2 .Checked = False Then
Chec ksox3 .Checke d = False
223
Chapte1 6

[1s t
Chcc~so,1 .ch ccl ,ta te 1..hcckState.I nde term ina te
c.nd If
t_nd Swb
ln l ..hn, t, ._ the t!'Lll numl-c-r l'I ,h.i
~,. . r.,d l'f°' ,, c,1h..ul,1led b, w,m g the
len gth
t, C\"'unt the ti,t.il num't..:1 \,t ,, ""I
l . ·r 1 pro per ly of the text box l-1
, " '1..• 111,t ,,pp1' ., n ,mlitn, n lo ven.lv
N'- II &\\.' I{ , h: , , , , '-'nl\ t\'1.l, th1..• , l 1e uc;cr has ent ere d
1 n tlw h,t,,1 "h,H,K ler, amI wo r d s a . owever
sel lo zer o. lf, how eveany lext in the ,
1
tl"\t ,n ll thi.-n t . , t m~th(•d 1, re
r' t1ie text bo te~t
J
1 u,1..•d hi n,u nt thl' wo rns, scp arn tcd
c;t\ _~ ma '-Uu • _.., by spa ces , and the res
~
" l m1\h tht.' kng lh (,! lhl'
,ma , ,., slorctl in a var iab le, wh 1. x has
,,~rd, entCJ\.-.J U\ th, h:'\I \"'I.,, ich contai· u tihng Words are
ns l e nu be
~ I ~ the F'S ki.', hl run th\' .,pphc,1tton ll'I r or
and 1.. hck the Find bul lon. The out
pul is sho wn in Fig ure _ :
._ Ow,\ k • s.,,..,i.
68
c ~13=•- - - -

,E :J

If:

Figure 6.8: Displaying the Inde


terminate Sta te of a Che ck Box
In Fisu re o Q, th1:. Cha rs cou nt che
ck bo, is selected and it disp lay
t~t 00'.\. s the tota l num ber of cha rac ters
ente red in the

,iJQ ..a; &a. ~

"'- •• NET •O~

J Wo,:i ,can

Tu.,. ...., . )1TI IAI- 5

Figure 6,9 : Displaying the Total Cha


ract ers and Wo rds in a Lab el
Exploring th e List View Control
Tiw L1-.1\ t\.' \' con
sim ilar to that folltrol 1<; u~•d to d
ow~d , th . isp1ay a hst . . nner
of item s, s uch as a list of col ors. . in a ma
:NET f-rJ m~" ork clac;!, Ii~ ~ ir;f1Jt It disp lay s the ,ten15
d fined in the
pan e of the Wi~ dow s Exp lore r win
., a~ foll ows : dow . The Lis tVie w clas s L~stVie\
1 p eme nts the Lis t View con trol . The '" class
inh erit anc e hie rarc hy of the
Sys tem .Ob Jec t
Sys tem .Ma rsh alB yRe fob ject
System.Component~ode1.C0111pon
ent
Sys tem .win dow s.Fo rms .con trol
Nnlt'w11rth y pub lic pro pt'r tws of System.window~.Forms Lis tv·1
the List View cta.,., Jrc
1,., 1(•·d in Tabew
le 6.5:
22 4
Windows Forms Controls - II

~ w orth~ ublic Properties of the LlstView Class


fable · Description
P7opertY - - - 1 ~ -cii-.----h-h--th-.- - - - - - - - - - -
Spe · 1es w et er e items are arranged automaticaUy by usmg the Alignment property
,wtoMrange -
1 • - Obtains or specifies the background color of the Lis tView control
_..-ckC~
1
10
8_:,__ - - ':._----+--:-~:;.--77----:-:---:------;----:-;----------------------;
Specifies either every item shows a check box or not.
~heckBCJ_OX'.'.,'.e:,:s:....----t~::::--:-:---:-:--::-::-::-:;:--:-::~-:-:-:-;:----:'.;-::----".':--:----:--::-:----------------;
l----=::kedindice.:s_ _-1,,_O_b_t_at_·n_s_o_r_s_p_e_cif
_i_e_s_th_ e_
i n_d_ic_e_s_o_f_th
_ e_
cu
_rr
_ en_t~ly;._ __s_._ _ _ _ _ _ _ _ _ _ _ _--i
ch_ec_k_ed_ irem
(heC _

~rtem_s______o_ b_ta_i_n_s_o_r_s_p _ec_if_i_es_ th_e_curr


__e_n_t_ly_ch
_ec_ k e_d_ it_ems
__ . -----------------·
---~c~ol~u:m~n_s
- _ _ _ _ _ _ ,___ __
Obtains or_ _ _ _the
specifies __ ____
collection __
of all the_ _ _ _headers
column _ _ _that
__ _in_the
are _List.View
_ _ _ _ _control.
___ _

Gr!dLin':e:,:s::....----i--:S':'p_e_c".':if::--ie_s_w_h"7e_the_r_th:-;e_gr_·_id
- ;-li-n_e":'
: s'"ar".~e-d_ra_wn_-;be-t-:-ee.-:-:
w n-:tw -;-o-i_te_ms:--
an_:
d -tw
-:-o:-s-u_b-:-:i'.te
"'.'_m_s_._ _-:-_ _-:-
~eselection
7
Specifies whether the selected items are kept hidden when the ListView conlrol 1s not
1
highlighted.
""Tt:~s · Obtains or specifies the list items in the ListView control.
~u!US~lect _ _ _....,~_
S_pe_c_if_i_e s__
wh_e_th_e_r_m
_ u_lb_·p_l_e_it_e_ms_can
__be_s_e_le_c_te_d_._ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _- ;
RightToLeftLayou t Specifies a value indicating whether the control is laid out from right to left.
scrollable Specifies whether the scroll bars are added to the control when there is not enoug,, space to
display the items in the ListView control.
Selectedlndices Obtains or specifies the indices of the selected items.
Selected! terns Obtains or specifies the selected items.
View Obtains or specifies the current view in which items are shown. This property can be set by
using any one of the members of the View enumeration. The members of the View
enumeration are: Smalllcon, Largelcon, Tile, List, and Details.

11,e Items property is the most important property of the ListView control. It is used to add and remove items to
and_ fro~ the ListView control. The Selectedlterns property contains a collection of the items currently selected in
a_L1st_Y 1ew control. You can select multiple items from a ListView control if the MultiSelect property of the
Li5tView control is set to True. 1n addition, a ListView control displays the check boxes next to the items, if the
CheckBoxes property of the ListView control is set to True.
Noteworthy public methods of the ListView class are listed in Table 6.6:
....!_able 6-6: Noteworthy Public Methods of the ListView Class
~
Method
Description
----------------------------~--------~-----1
--ear
Removes all the items from the List View control
Tostring
Returns the string representation of the List View control (determines the control type,
______________________JL_~co~un~~t~o~f~i~
tems, and the first item in the List View control if the count 1c; not 0)
Noteworth . --- - -
"r----- Y public events of the ListView class are listed in Table 6.7:
_able 6.7· N0 t --------------
1~ • eworthy Public Events of the ListView Class ""'
~
c1 Description
~-UlllnClick - ------- -
1 .:---.......__ ' Occurs when a column header is clicked
111Check --- - - -
~
s~ Occurs when an item tn the ListV.1ew control is checked or unc~ec_l-._e_d_. -------4
~dexChanged Occurs when the selected index changes
extChan - _ _ __,_ - - - - - - - - - - - - - -
ged I
Occurs when the Tex c property of the L.s tV 1 ~w control changl's
Youc - ----- ---- -- - - .
event~ use the SelectedlndexChanged event of the ListVicw control to handle item selections and ItemCheck
0
haocile selections of check boxes.

225
Chapttt 6

I h, I t. \ IL"' ,,,ntn1I uJ ,, plJ\ ' 1t-. ih'lll'- in tlw hill,," tn~ ti\ L' \'IL'"°" or m odes:
.
~ _ DL,,,Lt,, 1.u _.,. lll'lll' b, u,mg l.u~c ,cons (la rge icons arc o f 32><32
.J l~l' l ,on \t( '' r p' .
t 1 \ C'u c.in !-1.'t tlw, '''" l,t ,, \ 1,t\' 1L'" 1:onlrol to Iargc ico n mod e bv ixe1s tn s·1
C' •
...__
s v·iew prop
In\.. item 1.:, Ze) ne~t ,
setting 1-l
, , ....... JC\,n_ to
erty to
-.nullh ,,n , i,'" -Pi,pl,1 \ .. ,t, m-. b, ustn~ ,nMII ,cons ("mall 1co~s arc of 16x
16 pixels in size
, , 'I ou ,an xl tlw, IL'" ,,t ,, L1, lV1cw control lo lhc small icon
m ode by setting its y · ) next to the
\' t('\\ C:nullk\'ll •ew prope
rty to
.J u 1, ii:,, -O~r· 1,, ,n1.,II KL1n, ,,lw,,,-. in one col umn. "\ o u can set the view of a ListView c
'
i t-, . . _ ll·";. ,t, \ IL"" pn1pcrl \ ll1 \ l l'\\ List. ontrol to th I
e 11t
.l Dd .1.il, \IC \\ -Oi-.rb ~, 11cm, m mull1pk 1:olumn s "1Lh column
heade rs and fields. You can set th
.. ,1\ \l•nlr\)\ lL1 llw report modL' b, selling ib \'iew propert y Lo View .Deta ils.
e v,e,,•of
J Tile , ie" - D1,p\." , 11cm, a, fu ll--.,zcd Kon, w ith item labels and sub-ite
m inform ation You
, , ,, .i Li:-t\ iew 1.:,,nlr0l lo the Ille mode b, ..,cllm~ its Vic\\
properl y to View .T ile. · can set the
t..A,,1 ... n◊,,· learn "''" t0 u,c lhc l isl\ ,ew control in our \Vindow
. . . s Forms a pplications by creating
applirau,10. l\.lm,-J L1,t\'11." Control, which ,s . a new
also available tn the CD-RO M provide d w ith U1is book. After that
drag .:i L.i,t\ IC\\, J lc,1&,, lwo Button ,md a ComboBo, control fro m the Toolbo
x onto Forml . After that sci
the Tc,t rrof"rtic-- (1i the Button1 and Bullon2 control, Lo Remov e Item s a nd Add
Check Boxes respectively,as
-.hown m Fi~re t:-.10:

~
- ,_- - ...
~ ';" - - - -- ----.
.;,- :.l· .S ; ..,
-1. , , ..

.:.I . . .
El Ch....
1:
n. ,~ C E tJ lI .J
~c-., ~ \ r A'Qito
\l ~ Sl#thllboa " ~ l t
:l ~ T'f
~r- •
,;J

-
:ina.-.-
.a ....
ii
:-.·~
~
1 100~.lml £.:.i.r...

;:i...._
:~~
o - .... _ _ _ _j \ .J .i1] □ :::J ~
~ r-.,
'd ............,..c...,.,,,.,.,,.
l i....'-- , 3 u.u, .,..c-..rr-,
.) •·--•- 4

.. ,h,Pni,ed
r -- Jl Tonal 11'
...0 - -

Figure 6·10: Displaying the Design View of the ListVie wContr ol Applica
:--: · th L V tion e b)'
• O\\' u"m~ e i<.t · t sks on
lt!WControl application we have 1·ust created w e perform the following five
0~
I
a
J Adding itt!ms lo a L.st. 11 "',, control
..J Workin g with the s<>lectt•d ltl'ms of a - v .
1 1st. 1ew control
:.J Remod ng items from a Lt ,1 control

CJ D1,playing chL-ck bcn, ..s in a Li - r


"'W control
Q ~.. ttmg the \'i~w of d ,1st.Vie control
lt•t'._ now die.cuss lhbe al l c;l(:ps in d~tails.

Adding I tems to a ListView Con trio/


1101~
, L,,
) ou 1..in 1dd the 1tl'mc, to a L1,;t\ control at d
ll·w . .
wnting lhl' code lhl' Code Editor\ \ indo ·ndo\o\' or run id the
in ("i1g n lime e ither by us ing the Pro p e rti_e s ~ •1 , control to ,1l
w You nL•cd lo <;ct the itemc; pro p e r ty of L1s 1V,e...,.
226
Windows Forms Controls - II

u ~ing
. . tVieW control at d esign time. However , you can add the items in L1s tView control a t run time
jle01 5 •~ ~:thod of Ite m collection . Perform the following steps to add items
to Lis tV1ew control at d esign time.
property in
the A;l the Items pr~perty of Lis tView control by dicking the ellipsis button (.. ) beside of the Items
I. the Properties w indow. . . . . .
The ListViewl te m Collectio n Editor dialog box IS dISplayed (Figure 6.11).
In case,
dd items by clicking the Add button and change the text for an item by setting its Text property.
2· ~e have added five items- London, Paris, Tokyo, Berlin, and Mumbai (Figure 6.11).
Click the OK butto n to close the ListView ltem Collection Editor dialog box, as shown in Figure
6.11:
3. LlslV,cwltan Colc:daon Edi.la'

).lm,bns:

jI
0 Liff\ ..,.1-_ {Lmdot,)

~
i...,,..,...,_ ( Pau)
Lv1\·,...1- {T~)
.,
I.a<\-~
:'
,- --~
~---,
'J
I
i...,,·.... - (s..t..) r...•­

i ToolTipTc
t;,.i,..,.s,ylof..S.. Trw
I

I °""" ~·
--- □-•
~
~ □ <-,
St1teJ,,.,;:,dac □-,
.
T'!__

Lt=JI '--
Figure 6.11 Displaying the ListViewltem Collection Editor Dialog Box
The items are added to the ListView control, as shown in Figure 6.12:

"""'-~ -Da - . --
. . w t V ~ Momoflv...ls..A o

flt LIii ,_
il· :::i - i:, w.-Ji. .l '., .
.
---~"'"--

... L· !. 1 - - ~.

' --
---
• Al'lialDwtf--

- -- I
)I ..,
,.-.. ,...
~,c,■-, i

·--- !~
......'\r,ocrt T"')O
.....,_,. r...

-
a. ,. l .......... 1- 1
I.«.- U.I
o...a..
0
ci.doodladlo.
"-"-•-&..\'- -
c.a.n....~ I
c..-.
c-..1.-.s.,,,
D•'°""'"
o..s.,
r..,.,._...,
o......
-
'
--0 .J .,Z1_ al~,.
-::J - - \.t'..C..-r , 1 ,..,
, .........----
.,, ......
---
O.••-
~ ! . -...

..........
£-...
I
~ 0--
~ ~ -- - __
_ _ _J
J
ar- ..

Wi . Figure 6.12: Displaying the UstView Control after Adding the Items
orkmg .
the Se Wtth Selecte d Items of a ListView Contro l
· that a u:.er ~J~b at
tuntirn~ ~lnd exChange d event of ListView Control enables vou to dt:!termme the items
control's
h-tut~ j The Selected lndices property holds the md1ct:s of thosl' items th.1t are selected if tht> L1st\'iew
is set to True, othl!T\'I. 1~ sa\ that this proptrtY h1,IJ,; the ind~•x of a single st.•lt"\'.kd
ite,-,... . ect properh•
·;
\'OU L •ln
, . .
' ", 1n C with the 5elt.>etcd 1tem.s
of a listV~se the Mul tiSelect propert, is :,et to Fal"'-'· Pertorm the tullm, mg sll' P' tu wmk
iew control.
227

I 1 ~ t, u tn h.indlt thr '-'I. 1,, h .'~I
dlnd.,,Chring,>tl ~
l'\ <'nt ~ I.\
th;. ""- tf'dlndt ,t l\.'ln~t'CI L,, nt ()f tlw I 1c,tV ., , .
\c-- ~cl\angr,d )'\al ~(!ndf'r o\s Systel!l.ObJrct,
\\ \c.l ll'c:tedlnd('l'\(hanged
1
Bvv
I! ' '--0
"1 e
°,s
ntr I
1 I{('~ count , 0 lhc,,
~ou ha,c ~rl vcted:" ~ (L1~ tv1ewl.sclected1tems(o)
-ltllt)

,, n,mlt '-(1,-c, rn ,1Pm 1n 111,• 1 ,~1, 11•w < 11n1r ..1 111'" 1(', x ,d •
., h "n in I 1hur1: h 1'\

-- 11 1 lSpi.1! ~

-- ,.

F°'tq\m C. tl Handling the SoloctedlnduChnngod Evont of llstVlew1 Control

Rf:!7. ~.. items irom !Jst\lie11 Controls


n, ,,. , a, runtmw b,· wnttn~
. . l
tlw ••'• ·
I:' 111 C.,J c, l:.d 1tor Perfom1 !ht

, ~ lkm,; button m th, dC><;1gn "'•''' .:ind .:idd th~ tollo"


. :i
mg cote 501 pp~t to the

Lrt Uhc\.(Ci)'\al st-nder As s,ste!ll.Object, Byva1 e As System.EventArgs)


Cltci
ltt'%5 .Rr~ e(L h t\ l e11l . 5el ectedl tems (0))

~ Pi tl'\ ands. l,~t .in 1km Imm L1!>l\'1ew 1 control.


•ton to h.m o, ~ th, 11, ms, ao; ,huwn m Figure 6.1-1
~ '-

Figure 614· R
•rnoving •n Item from a llat View
228
Windows Forms Controls - II

wl control, as shown in
~ l k tlw lk nllWC Item-. button the sdt'Cted item rcmov~d from the Lis1Vif
\~ \ l1ll,
f1fUll' 11 tCi

_.J

Figure 6.15: The LlstView Control after Removing an Item

o,splaying Check Boxes in a ListView Control


by setting its CheckBoxes property to
)ou can display the check boxes beside lo the items in a ListView control
g the ltemCheck event of the ListV1ew
True You can also handle the selectio ns of the check boxes by handlin
control in the code. Perfo rm the following steps to do this:
I Double-click the Ad d Check Boxes button in the design view
and add the following code snippet to the,,,
Code Editor:
e AS System.EventArgs)
Private sub Button2_C1ick(ByVa1 sender As system .Objec t, ByVal
Handles Button2 . C1ick
Listviewl.checkBoxes = True
End Sub
2· Press the FS key to run the a pplicati on and click the Add Check Boxes button to add the check bo'\es with
each item of ListVie wl control, as shown in Figure 6.16:
., Form! Qa- -
r--,=--
I ~

,- L.;
"-
.:
Tok)o

-I
:::.J

I --
1
[Lwi... .
I

f,dd<>i1- J .
--
S Figure 6.16: Using Check Boxes In the LlstView Control
etting th .
A~ ct· e View of a ListView Control
w control La:gek on, icw, Report view
(also•scussect earlier, there are four different h pes of views m the List\11e
t? these news lrom ~ther, '~" !.> b}
a~s,~~llect _Details view}, Small Icon vie\\ , Jnd List view . '\ ou cJn S\\ itch
\ IC\\ SmJlllcon (which equals 2), or
Vi~, ng V1cw.Largelcon (which cqu,)b O), Vil' W Dl'l,,il, (,, luch L'<JU.US I)
) Pcrtorm the followin~ .;tcps to
llo l~i~:'st (Which equals 3), rcspcl"t iwh ti, the L1,t\ U!\\ conlrl,l''> \ iL''' pr0~rl
1
oi Forml.
Double-cl ick the Form I ,md .,dd the IL,lllm ing code snippet to the Lo.1d e,·ent
229
Chapror 6

Private Sub rormLLo.,d(s,,ral s1?ndl'I' ,b System.Object, ByVal e As system.EveritA


Handle;; !of\Ba,c.Lo.id rgs)
t:~ooeo,l.Hern<. . Add\ L,,rge Icon View")
COC:boBo, l.Iteci'-.AduC small Icon View")
tocl)oSo, l. lt em~. Adel (" L, , t View")
CO!':bo80\ 1. ltcms .Add ("Tile View")
lnd ~ub
In th • 1,m.wu11• ,~il' '1111'}"-'l '"-' h,n l' ,1tldl'd three 1ltm1s lo Combo Bo\.} by using the Add rn th
t
~'1IC\'.taon lh~-c th.'n~ wl1rl-.. J,. l'pllt1ns. ft1r lhl' usl'r to ~e Il'Cl a view
. for Lhe Lis
. t View
. control at e od
. of 1·1s Items
.. AJJ the fl,llo\\ m~ c0de ,111ppl't ,is sho\\ n in L1s ltng 6.10, to the Code Editor for settinruntJ tune..
LL,t\ 1c,,· ctmlrl,I· g ie view of the
U,tin~ t..10: lllu, 1r 1tm~ lhc Code tor ~tltng lhe View of the ListView Control
P;i ~ate sub comboeoxLSelectedindexchanged(Byval sender As System.object, ByVal e As
S)~~ec.E~ent4rgs) Handles Comboeoxl.Selectedrndexchanged
lt co~boeo~l.selectedrndex = 0 Then
L1stviewl.View = View.Largercon
Elseif comboeoxl.Selectedrndex = 1 Then
L1stViewl.V1ew = View.Smallrcon
Elseif comboeoxl.selectedrndex = 2 Then
llStViewl.View = View.List
Else
ListViewl.View = View.Tile
End If
Enc sub
3 Run th!! application bv pressmg the FS 1-..cy and selecl a view from the combo box, as shown in Figure 6.17:
•_. f.cr-itl

[ .i,;,i o- r... )

1..::::=---===~i.. ---
i'L-.

_ \!
........ - - - ,(n.JI
-.JZ:libiiii
lave"""\ltw
·--·

Figure 6.17: Changing the View of List View Items


-

in
~\tlcr
,·1~ur~<.clt>cting
6.JS: a vie,, from the combo box, the view of the items of the Tile View control changes, as shown

r..,.
-
Figure 6.1 8 : The LlatVlew Control after Cha~glng Its View
230
Windows Forms Controls - II

~ e TreeView Control
oe inl , View contro l is used to display a hierarchy of nodes that mav include various child node~ The
f he _Tre~1 ip between a Tree View control and its nodes can be compared with the relationship between a trel.' and
(nod es) ·ma manner similar to lhat followed m thl' ll'll pane of
relations
' es A TreeView contro 1 d"1sp 1ays ·items
•t branc 11 · . .
15 Windows Explo rer window, where the hi~rru:chy of folders on the computer's hard disk is dis ~•la} ed. You
the , d and colla pse the parent nodes by clicking them.
can ex pan
T eView class d efined in the .NET Framework class library implements the TreeView control Each node in
~~re:~iew contro l is a Tre~Nod_e objec~ that is implemente_d by the_TreeNode cl~s defined u1 the .NEl
k class librar y. The inhentance hierarchy of the TreeView class 1S as follows:
Frame\I/Or
s ystem.object .
s ys tem.MarshalB yRefObJect
system.compo nentModel.co mponent
system.windo ws.Forms.con trol
system.windows.Forms.Treeview
Noteworthy public properties of the TreeView class are listed in Table 6.8:
Table 6.8: Noteworthy ~ublic ~o'!erties of the TreeView Class
-----
Property ~-------. Description
BackColor
- -- - - -
Obtains or specifies the background color £or the 'I' r eeView control
Obtains or specifies the background unage for the T r eeView control
------ ----- ------ ----- ---
Backgroundima ge
Backgroundima geLayout Obtains ~ specifies the layout of the background image for the T~ ew control

BorderStyle Obtains the tree view' s border style


CheckBoxes ------ I - - -
Specifies whether or not the check boxes are d1Splayed next to the tree node-.
ForeColor Obtains or specifies the current foreground color f~r ~eev.:.::..w~trot
Nodes Obtains a collection of tree nodes in the TreeView control
- PathSepara tor Obta ins or speci fies the delimite r stnng ust>d bv the tn:e not.le p.ith

--RightToLeftLa yout
Scrollable
Specifies whe ther or not the Tree 'i~w control is laid out from right to ldt
Specifies whe ther or not the TreeV ~ew control t.11:,plays the
need ed
51..,oll bars when thi?y .ire

_ SelectedNode
ShowLines
Obtains or specifies the tree nod e currentl y selected in thl! r .,.. ' : e w ,ontrol
Specifies whether or no t the Imes a re drawn betw...cn the tree nodl"• m the TreeView
------4
control
ShowNodeTool Tips Specifies w hethe r or not the plus-sign (+) ant.I minus-sign (-) bu llvll!o Jre J i.,plJ\'eJ next
- ShowPlusM·1.nus
to the tree nod es tha t contain the child tree nodes

- Sho;;oo~t:L1.nes
;--;-.-------
- Specifies whether or not the plus-sign (+) a nd mmus-s1gn (- ) huttons .ire dic;pl.iveJ nt!lll
to the tree nodes with child tri?e nod es
Specifics w he ther or not the Imes arc drawn b,.,tw,-en the tree nuJc.-,, tha t dr,• at tlw wot tlf
~--
"" so;;r;t:e:;; d--------
the TreeView control
Specifies whetht>r or not the tr~ nndl'" a_re sorted
Text
• - Obtains orspec1fies thetext oft he ':'reE.V1e· ,ontrol
-2_0 PNocti":e: -------- Obtains the fir;t visible tree node m the Tree •• ,., control
----
Visii·b:;-;:: ::-_:-------
1. lecoun t Obtams the number 0 1 noJes that ,uc currt>ntly viewlll through the T reeV 1ew n>ntr~

~e Nodes and Selec te d N ode ro e rties are the two most im porta nt propertie5 of the TrceV1~,\ control. Tht•
des pro perty • d ddp pd nod es to and from the Tree\'1e,, control and the Sclec tedNo<lt.?
Pro 1s use to a a n remove
perty is u sed lo set a nd re trieve the currently selected nod e in the Tree\ lt:>V\ control.

231
ChlJ:tr'i 6
~,l.. \II ti-, l n,•\ d,1 ,, lt ,kd
I\' \\ ll\' In l ,,b k h .ll.
' ••b'i~
lab!f 69 !\, Oll'IWl"Orth \ P" ' M~thod!> of tho Trc cVl cw Cla ss
Mf'thod Oescnptlon
(. ,,lur"-"" .,II tlw IWl h' llll ludl tl~ .,II the d11ld
- node<; tha t arc j ll
1,r,.mJ , .,II tlw ltl'l' 0\1 \k, _ n ,e 'I'r-eev --
{;- ---
- ~ ctln1to1
l,( t, tlw mxh· tllJI ,, ,,t ., '\''-' lllll
'd 111\Jlllll\
Get , tlw numt,,: r ,,1 lll'l' 1wd ,·, (1t
11pl1,111all\ mdu de.. , nil the n o
d es · lh
·- - -
,,,1 , .ill tlw 11,·m, m tlw · , _1 w l\\nlrol - in c sub-t
· · ___reesi
K\'lum .. ., ,tnn g rl1nt,1mm~ ti\\' n,,m
e of lhc con t rnl
, ,rtt,, pub hc l'\ \ -:11, l,1 tlw l n..·l•\ WI\ d,N , ,ire 1i.... tl'd
in T..1blc 6 .10 :
..able 6.\0 Not ,~o rthy Public Eve
nts of the Tre eVi ew Cla ss
Effftl Description
(\.c u~ ,,he n we dw ( I...., n,, dl•·., che
ck bo'\
------------~
-l\.
_ .--_
u r.._,_' _h_l - J lr.:c n('ldc rnll aps es
fy
..
1 ci.lur-. "h.:"nn "l' c,p.rnd ,, tree nod e
l C\:cur, wh1.:n ,, c '-l'll'CI a trcl.? nod
e
I Ocrur, \:lelore we (hl'Ck a nod e's
~---------_.....,____
C\.~u~ \:lelore a n0d e coll ,,pw s
t-- :-- :--- - -- - - - - - 4 -0c
che ck box

_ cu_~belore we e,p and a nod e


Occur., ~fo re we edit a nod e·s labe
l text
r- -- -- -- -- -- -- 1. ... .:.0ccur.; bd?re
we select a nod e
~-: -:: ::- --- --- --- --- --1 ....
:°'
::.::
:cu.:.:.:..r:.,':.:,'·.:,:hen "e ~tart dra ggi ng ~n
od e
r;- -::: :-- --: :-- -:- --- --- -1.
...:(:..:.:'('.
\: U::.: l".\: .':.:.'':.:
he::,:n.:..::we chc_k_a_T r e e No de obje ct
·~;---:::---:--:-:---•-0:.__4_ :;c.\:;::·~cu::,:rc.~_:":,:·h:;cn
" e dou ble-chck a Tre e No de obje
-;:-: ---: ---- ::-= :--:- -:::- :--- --4. ..::° ct
cu::,:r,:::,._:1':_:h~cn the mouse-pointer hov
':,·: :,:
ers ove r a Tr ee No de object
r-r:-:-----------1
~(.\~- :l~U:r<:,_:1~,~h~en~lhe value of the Pa dd
ing p;p ert y~c~l~,a'.1.;n~ g~e :s:'. ----
r7'-:-:-::-:-;-:'.""."':--~---l-O~·c: .: :ur<, when we draw a Tre eVi e ~jectt --- ---
- -- -
j-;::-;:-::::::-;-..;..---.::.::...,i_~c~
-1e" l 0c
ur~ when- the value of- the R1- .gh -- - - ·-
--- -:- ;:- ::: ::: ;-
-- -- -- -- -- -- -. L .: ;0.::_:·cur,- tT0 Le ftL ayo ut pro per t), chan ges
- ::- -
whffi the valu e of the Te x t pro per
0

ty :c~
h:a~n~g:e:s_ _ _ _ _ __ _ _
The mh em.ance tucrarchy of the Trl·c\
S)S t~~ -Ob J ect ! d . - - -
o ecl ass rsa sfo llow s:
Sys tet" t.~4 rsha leyl lefo bjec t
Sys ten .w, nd° "s.f orms
Note\\ , · • .., 1
f u ..,. rr p, rt • nl the Tn:· \reeN d
ode
lic Propertl ~
Tab le 6 .11 Noteworthy Pub 0
e clas s are listed in Table 6.1
Property 1:
es of the TreeNode Cla ss'..,__ ,:__ _ _ _ _ __
_ _ _ _ _ _ _ __
Description
r
--: ::- :;- -;: :::" 'i1 --- --- --;
t-"': =:": :~'. ':::-- - - -- --~
--;(;....__
.1t~t.s
: !·"~\~
. t•:r~
~p(~·cif'1"" 1h
c background colo r of a tree nod
~- -~y,,'C if., wh{•lhcr o e
r-: -:: :-: ::: :-- :-- -- --- 1_ :~b 0
t., ,n, thnh o
- _ r not a lrt:c nod e is che cke d -
---
• r •P 01,
ur - ~ mi:~u _associated with
r
i-:-;:--;-;:--;:---~----f➔
-;-:-;-:-::;;---------+➔0;;:
1 the con cern ed tree nod e

r
=~o~r~,~~~•~li•~"'>~t~h0h ~ e c !!ode

2
rr;ji;';;----------f-;:2; Obu.
Ob
1,;run\
:=~:!~
1
~n;s~
;,!!~~
lh,, lir~,

th~c~ p~4~
ch111•·;~ ortc

th~f~
-- --ut men u
' tri~• noclc 1n the 1r1:e nod e coll ecti
h onc erne
associal ed w1th t e c . - -
on
--- --- --
~~ ~~
rom lb1: roo1
23 2 - - - - - - - - - - - - - L -~~ta~1~n!s~th~•~·l~•JQi~h~~~n!cf~~~ ~tree_nod e to _the ·
.
cur renl
:..,::,:
· tree n<:de
_
' a IH·t• node in the tree nod e coll_::.,;.._ _1_0
cct !.,
Wind ows Form s Cont rols - II
-
-
orthy Publi c Prope rties of the TreeN ode Class
. Notew
-- Description
. 1.
Ta ble61
propertY ppec ifics whether or not the node is expanded -
fx,in led
Specifies whether or not the node is selected --
~ e c ted
I Obtains a value specifying whether or not a node is visible
~ is lble r
L
Obtains the last child node
---;:;st Node T reeV iew cc>nlr~
Obtains the zero-based depth or level of a tree node m the

--
- Level
Name
I
- Obtains or specifies the name of a tree node
Obtains the next sibling node
Next Node node
Obtains a collection of the objects assigned to the current tree
- Nodes
Obtains the parent tree node of the current tree node
rarl'n t
.--
PrevNode -
Obtains the previous sibling tree node
node
Obtains or specifies the data displayed in the label of a tree
Tc1g
Obtains or specifies the text for a node's label
Text --pomtcr hovers over a
ToolTipT.;,xt Obtains or specifies the text that appears when the mouse ,,
I
' Tree Node object
---
....TreeView
- I Obtains a node' s parent tree view
you
I
ode objec t by settin g its Text prope rty. ln addit ion,
You can set the text for the tree node label of each TreeN of the
ning an lmag eList contr ol to the lmage Lisl prope rty
can display the imag es next to the tree nodes by assig y the check boxes next to the
a tree node . You can also displa
parent TreeView contr ol and assig ning an imag e to select or clear the node s
s prope rty to True. You can then
nodes of a TreeView contr ol by settin g the Check Boxe ode objec t conta ins
or False . The Node s prope rty of a TreeN
by setting the tree node 's Chec ked prope rty to True s uch as
TreeN ode objec t. You can use expre ssion s,
the child TreeN ode objec ts for the curre nt t. The
. You can add, remo ve, or clone a Tre~N ode objec
MyNo de.No des(3 ).Nod es(S) to refer to the child nodes
to add or remo ve the node s at run time.
Nodes collec tion's Add or Remo ve meth ods are used
listed in Table 6 12·
Noteworthy publi c meth ods of the TreeN ode class are
...2!,_ble 6.1 2: Notew orthy Publi c Meth ods of
the TreeN ode Class
-- --

~ thod
~ Colla pse
Description - -
Collapses a tree node
Expand !
r--;. Expands a tree node
~ExpanctA11
Expands all the child nodes
~No cteco unt - ---
Gets the numb er of child nodes of a tree

--
Remove
Toggle
-...:. ::_ !-
Removes the curren t tree node
-- - - - - - - -;tate,:;
Toggles a tret! node between the e,pan Jed and collap~t?d
--
--- ' Returns a-- -
1
Tostr ing
string that represents the curren t ob1ect
Let's now I
-- - -- .- - - s appli.catio. ns ~y de~elopmg a new apphc. at1on
ows Form
.
named Tr ea1:° how to u se the tree views in our Wmd mg the
in the CD-R OM provi ded with this book After creat
TreeVie eeYie wCon trol, whic h is also availa ble l .ind
ox, anJ a Butto n contr ol from the Toolb ox to form
set th TWControl appli catio n drag a TreeV iew, a TextB e 6.19
Boxes , a'> ~how n m Figur
e ext prope rty of Butto nl contr ol to Show Chec k

233
Chaptt 6

• I •

,.
u:::..,••,
T*"'-l la...
l u,
llr•-.--..11t\l► Dllltrll(

'--!,,..._ . :, .
~'JU 1.r:.
~ __ .,. .,.,~Ctlpt91
. a ,....u,,....na
• \11 ... - t

Figure 6.19: Displaying the Design View of the TreeViewControl Application


t.:~ ~ Tn.>c\ ti?\\ l.untr1.."'l .1pphc.1111..m. WI? pl?rtc:inn tlw follow111g three tas"5 o ne by o ne:
.J Adding node-- to a TreeV1 control
J H.mJlm~ the A!:· er.:<"lc l'\ cnt l,( tlw Tret \'ie·..i contro l
.J Di.~lann~ cht'Ck l,1,...-._ in J • _- control

Adding Nodes to a Tree l,1ew Control


) ou c • 1 r "-1•-. t a Tr1.."\. \ 1cw control at de!>ign time either by using the Properties window or at run time by
,\nt1ng co<lc m the Code EJitor. To .idd node., to a TreeV1ew contro l at des ign time, yo u need to set the No~es
prOf>L-rt, of the Tn~\ 11.·\\ control \ ou nt-ed to U!',e the Add method of the Nodes collection of the TreeVie11'
I d
c ntro to a d the nod ....., h• .1 Tr...~\ Il!\\ control. Perform the following s teps to add no es to a T re eView contra1
.:it dl..,.lf!Tl time.; d

~•t the Node prof)\!rt~ ofTr1."1?\ tel\ control b\ clid-ing the ellipsis button ( ... ) beside of the Nodes property
m the Properti~ \\indow ThL Tn:e'\ode Editor dialog box is displayed (Figure 6.20).
2 . . the Add Root button and the child nodes by clicking
AdJ the root nodes by clicking . the A dd Child
. ·tbutton
Text
to the T r~l"Jode Editor dialog box, and also change the text to be displayed in a node by setttng I s
proper!) (r,~rc o.20).
3 01ck the OK button to do-.e lht! Trl"l!Node Editor dialog box, as shown in Figure 6.20:

li

·-........

)( ·- JI

-~-
r.-c.i,,

...
8~·
·-
.I

·-.......
T...-r•r•
0.....
c.... ' -
'-''-"'>r
~ .,
(

,...
-·..,..,
a-·
,_...._.Joo., ni~ ,-...;,.,

""'- .................""."""--
""'- ·~ c....

Figure 6.20: Dlaplaylng the TreeNode Editor Dlalog Box


234
Windows Forms Controls - II

. k the OK button the nodes are added to the TreeView control, as shown m Figure 6.21:
,0 0 , clic ....
,\Ci \ • r-•~ ~~-- ...,. ·
n,..,._..., _..,a.ji,, ;-llllo _ _ ..._..,_ _.,.
;J • _l " .J "'" ... .,.
-4 1 ~ .1 - • -

~
,;
!.f',-,f~

.., .........
,
S,,,r.-v.C«.11~
""'-' 0

'°""""
..
~ ··
.. ~

--
rn ',J,c..,._
\Mllilbri rnirM
·I· Sp. '"t
~ i c . - -,
L ,-.,-....1~
l •"Jf.•rr'X
Ttt~-'
l
0 b
,.. T"t'SO'\
0 r-
,, fnoi5.'T1! 4 .i':i) :il '.lltl
J:i T ~ - -;;w...1-•-c -.aro ,-
., ~ r,_,..,.c.'"'
1;.
0
1 ..11,..
-nu.S• ,. ,,._,
\ r,.,..n,., :J•..t••
:: \ ~,,;!i-

~ "~~'Ml
c-~"
c-

Figure 6.21: Displaying the TreeView Control after Adding Nodes

Handling the AfterSelect Event


of the Treeview
You can determine which node the user selects at run time by handling the AfterSelect event
control. Perform the following steps to handle the AfterSelect event of the TreeView control:
1. Add the fo11owing code snippet to the Code Editor for handling the AfterSele
ct event of the TreeView
control:
Private Sub Treevi ewLJfte rselect (ByVal sender As System.Object, ByVal e As
System.wi ndows . Forms. TreeVi ewEventArgs) Handles Treevie wl.After select
TextBox l .Text = "You have selected : " & e.Node.Text
End Sub
2 selected item is
· R~n the applicatio n by pressing the FS key and select an item in the TreeView control. The
displayed in the text box, as shown in Figure 6.22:
■J forml

c -------
~ Q,t,ons

I
I
,' Fnl~
- Sea,,,d01,ao,,
C
Ill
I
E

~ ~- 1

D· Figure 6.22: Handling the AfterSelect Event of the TreeView1 Control


isp/a .
1're Y~ng Check Boxes in a TreeView Control h • ......
e vie l'('11. LI\Y,t':- t~ a
1'reev· Ws also display check boxes !>imilar to lho!>e \ ou use m menu items. You can display the c
tht.> folio\, mg
tew control bysett·mg the Ch ec"•so,e-. property. of the Trttt.''v ti.'\'\, control 1.;; to True Perform
ste tod·
Ps
tsplay check boxes in a Tree\ 'iew control·

235
Chaptu6

o::a.,_,
f~"-t , ...."
1,,.
n.-.i....__. ...... ,.....

Figure 6 19. Displaying the Design View of the TreeViewControl Application


l: ~ ~ Tn.~\ ...... l....'1ntrnl Jpph1..JIIL,n. "l' l'l'rlorm the follow mg lhree tasks one by one:
.J
AdJms nod(", to .1 7ree\liew CC'lnlrC'll
.J
H.indltng the • .. r,. • • L'\'1.•nt nl the ,::
ew control
.l
control
Adding Nodes to a TreeView Control
) ou c. ... lh, Lr J Tn.-e\ 11.' \, control at de,ign hme either by using the Properties window or at run time by
\, ntm~ code m the- CC'dc FJi1t1r fo add node,, to a Tree\'1ew control at design time, you need to set the No_des
Propert\ I o:dd the T rc-e\'ie,, control '\ ou llt>l-d to u,e the Add method of the Nodes collection of the TreeV,ei~
h
contro to a
.st Jl:",Jgn bfl'll:' t e noJ~ to a Tr1.~\ 1cw control. Pt•rform the following steps to add no d es t o a TreeView contro
1
~t the ~odC' property ot T r1.'I.'\ 1c,, control b, cl1ckmg the ellipsis button ( ... ) beside of the Nodes propert}'
m the f>ropcrtw.., Mndo,, The Tr~'.\lode Editor dialog box is displayed (Figure 6.20). ti n
2 Add
10 . .
th the root nO\fos by cl1cking the Add Root button and the child nodes by chckmg the . . Add Child bu
. •ts Texto
t! frce!\:odc Editor dialog box, and alc;o change the text to be displayed in a node by seth ng 1
propert) (Figure 6 20)
1
Clid, the O K but n to clo -c tht= T rt=t=Nodc Editor dialog box, as shown in Figure 6.20:
-
--• t::J
.....
D ,

. .._"'-~-~
t...rr.r..
c-...

6 20
Figure - · Dlsplaylng the Tree Node Editor Dialog Box
234
Windows Forms Controls - II

Tree View contr ol, as shtm n in Figu re 6.21:


. k ihc OK buLLon the node s are adde d to lhe
CIJC • :iliiilif
i\' 1·0l
I
1 ,_,...c.......,, __,, ''::°' ::':_ _ _ _
..,
,_ - • - ..,_
ft, fn ,,._ " - - 36of Tia Doo l . . -
;J·,;.J ·Jlir lJ i,:J ,, ..... .... . -.
J !..l - •• ~;> :~

~ s.r,~
,,..,
CD

~

~.,.Con1c ::f.,.,
\ ph1Ca:u.11t•l'f
0
,_ --0.------...,r fnnll
.,. I
~........,

--
~f,..'"1 ~ r e . a -,
l!,a, •W!'fT bc>l,:s wt
L
T1Y·c,r,1ro (

ft1.0L..r, -nl.P~
I
o b T ilt---• --?e.\....
~
.t' r~Bo\
0 T-,
~ ~ll JJ~
J•
J:i
Tf'll"lSrnp
T-. •~ o- ---o -- 0 -;i-~ ----apa,
~,,..,, ...c...i
~ Tnmr
,.iii-,, ..•
.::J f....t,-•

rol after Addi ng Nodes


Figu re 6.21: Disp layin g the Tree View Cont

Handling the Afte rSe lect Eve nt t of the Tree view


ts at run time by hand ling the AfterSelect even
You can deter mine which node the user selec
the AfterSelect even t of the Tree View control:
control. Perform the follo wing s teps to hand le
t of the TreeV1ew
Code Edito r for hand ling the AfterSelect even
1. Add the follo wing code snip pet to the
control:
Private Sub Tree view LAf terse lect( Byv al send er As syst em.o bjec t, Byval e As
l.Af ters elec t
.Forms.TreeViewEventArgs) Handles Tree view
System .windows & e. Node. Text
Text s ox1. Tex t = "You have se1 ecte d: "
End Sub
selected item is
2 and selec t an item in the Tree View contr ol. The
· R~n the a pplic ation by pres sing the FS key
displayed in the text box, as show n in Figu re
6.22:
o:} Fom1l

I_You tir.e .-Sod D

t of the TreeVlew1 Cont rol


Disnt. . Figu re 6.22: Hand ling the After Sele ct Even
1-JaYmg Ch trol .
l'reevi eek Boxes in a Tre. eView Con . y an fo-play the ch.x k boxt ·, m c1
l' reeVieews also d'isp 1ay chec k boxe s s .imila r to those vou use m menu items . ou c .l ·
.
th 10110" mg
1,; to frue. Perfo rm C'
steps to~-c ontro l by setti ng the Chec kBo, es prop ertv of the Tree\! 1ew control
'
u~P ~y ch eek boxe s in a Tree Vie\ , contr ol:

235

You might also like