Tải bản đầy đủ - 0 (trang)
Chapter 12: Working with Collections and the System.Collections Namespace

Chapter 12: Working with Collections and the System.Collections Namespace

Tải bản đầy đủ - 0trang

classlibrary.UsingSystem.Collections,youcanaccessseveral

usefulcollectiontypes,suchasStack,Queue,Dictionary,and

Hashtable.

VisualBasicnolongersupportscontrolarrays(collectionsof

controlsthatsharethesamenameandareprocessedasagroup),

andyoucannotgroupcontrolsbyusingtheClipboardasyoucanin

VisualBasic6.However,youcancontinuetostorecontrolsinan

arrayifthearrayisdeclaredintheobjecttype.



WorkingwithObjectCollections

Inthissection,you'lllearnaboutcollections,apowerfulmechanismfor

controllingobjectsandotherdatainaVisualBasicprogram.Youalready

knowthatobjectsonaformarestoredtogetherinthesamefile.Butdidyou

alsoknowthatVisualBasicconsiderstheobjectstobemembersofthesame

group?InVisualStudioterminology,theentiresetofobjectsonaformis

calledtheControlscollection,whichispartoftheSystem.Collections

namespaceprovidedbythe.NETFramework.TheControlscollectionis

createdautomaticallywhenyouopenanewform,andwhenyouaddobjects

totheform,theybecomepartofthatcollection.Inaddition,VisualStudio

maintainsseveralstandardobjectcollectionsthatyoucanusewhenyou

writeyourprograms.Intherestofthischapter,you'lllearnthebasicskills

youneedtoworkwithanycollectionyouencounter.

Eachcollectioninaprogramhasitsownnamesothatyoucanreferenceitas

adistinctunitintheprogramcode.Forexample,asyoujustlearned,the

collectioncontainingalltheobjectsonaformiscalledtheControls

collection.Thisgroupingmethodissimilartothewayarraysgroupalistof

elementstogetherunderonename,andlikeVisualBasicarrays,theControls

collectioniszero-based.

Ifyouhavemorethanoneforminaproject,youcancreatepublicvariables

associatedwiththeformnamesandusethosevariablestodifferentiateone

Controlscollectionfromanother.(You'lllearnmoreaboutusingpublic

variablestostoreformdatainChapter14,“ManagingWindowsFormsand

ControlsatRunTime.”)Youcanevenaddcontrolsprogrammaticallytothe

Controlscollectioninaform.

Inadditiontoworkingwithcollectionsandobjectsinyourownprograms,

youcanuseVisualStudiotobrowseyoursystemforotherapplication

objectsandusetheminyourprograms.



ReferencingObjectsinaCollection

Youcanreferencetheobjectsinacollection,ortheindividualmembersof

thecollection,byspecifyingtheindexpositionoftheobjectinthegroup.

VisualBasicstorescollectionobjectsinthereverseorderofthatinwhich



theywerecreated,soyoucanuseanobject's“birthorder”toreferencethe

objectindividually,oryoucanusealooptostepthroughseveralobjects.For

example,toidentifythelastobjectcreatedonaform,youcanspecifythe0

(zero)index,asshowninthisexample:



Controls(0).Text="Business"



ThisstatementsetstheTextpropertyofthelastobjectontheformto

“Business”.(Thesecond-to-the-lastobjectcreatedhasanindexof1,the

third-to-the-lastobjectcreatedhasanindexof2,andsoon.)Considering

thislogic,it'simportantthatyoudon'talwaysassociateaparticularobjecton

theformwithanindexvalue,becauseifanewobjectisaddedtothe

collection,thenewobjecttakesthe0indexspot,andtheremainingobject

indexesareincrementedby1.

ThefollowingFor…Nextloopusesamessageboxtodisplaythenamesof

thelastfourcontrolsaddedtoaform:



DimiAsInteger

Fori=0To3

MsgBox(Controls(i).Name)

Nexti



NotethatI'vedirectedthislooptocyclefrom0to3becausethelastcontrol

objectaddedtoaformisinthe0position.Inthefollowingsection,you'll

learnamoreefficientmethodforwritingsuchaloop.



WritingForEach…NextLoops

Althoughyoucanreferencethemembersofacollectionindividually,the

mostusefulwaytoworkwithobjectsinacollectionistoprocessthemasa

group.Infact,thereasoncollectionsexistissothatyoucanprocessgroups

ofobjectsefficiently.Forexample,youmightwanttodisplay,move,sort,

rename,orresizeanentirecollectionofobjectsatonce.

Tohandlethiskindoftask,youcanuseaspecialloopcalledForEach…

Nexttocyclethroughobjectsinacollectiononeatatime.AForEach…

NextloopissimilartoaFor…Nextloop.WhenaForEach…Nextloopis

usedwiththeControlscollection,itlookslikethis:



DimCtrlVarAsControl

...

ForEachCtrlVarInControls

processobject

NextCtrlVar



TheCtrlVarvariableisdeclaredasaControltypeandrepresentsthecurrent

objectintheForEach…Nextloop.Controls(notethe“s”)isthecollection

classIintroducedearlierthatrepresentsallthecontrolobjectsonthecurrent

form.Thebodyoftheloopisusedtoprocesstheindividualobjectsofthe

collection.Forexample,youmightwanttochangetheEnabled,Left,Top,

Text,orVisiblepropertiesoftheobjectsinthecollection,oryoumightwant

tolistthenameofeachobjectinalistbox.



ExperimentingwithObjectsintheControlsCollection

Inthefollowingexercises,you'lluseprogramcodetomanipulatetheobjects



onaformbyusingtheControlscollection.Theprojectyou'llcreatewill

havethreebuttonobjects,andyou'llcreateeventproceduresthatchangethe

Textpropertiesofeachobject,moveobjectstotheright,andgiveoneobject

inthegroupspecialtreatment.TheprogramwillusethreeForEach…Next

loopstomanipulatetheobjectseachtimetheuserclicksoneofthebuttons.



UseaForEach…NextlooptochangeTextproperties

1. CreateanewVisualBasicWindowsApplicationprojectnamedMy

ControlsCollection.

2. UsetheButtoncontroltodrawthreebuttonobjectsontheleftsideof

theform,asshownhere:



3. UsethePropertieswindowtosettheNamepropertyofthethirdbutton

object(Button3)to“btnMoveObjects”.

4. Double-clickthefirstbuttonobject(Button1)ontheform.

TheButton1_ClickeventprocedureappearsintheCodeEditor.

5. Typethefollowingprogramstatements:



ForEachctrlInControls

ctrl.Text="ClickMe!"

Next



ThisForEach…NextloopstepsthroughtheControlscollectiononthe

formonecontrolatatimeandsetseachcontrol'sTextpropertyto

“ClickMe!”Theloopusesctrlasanobjectvariableintheloop,which

you'lldeclareinthefollowingstep.

6. Scrolltothetopoftheform'sprogramcode,anddirectlybelowthe

statementPublicClassForm1,typethefollowingcommentand

variabledeclaration:



'DeclareavariableoftypeControltorepresentfo

DimctrlAsControl



ThisglobalvariabledeclarationcreatesavariableintheControlclass

typethatrepresentsthecurrentform'scontrolsintheprogram.You're

declaringthisvariableinthegeneraldeclarationsareaoftheformso

thatitisvalidthroughoutalloftheform'seventprocedures.

Nowyou'rereadytoruntheprogramandchangetheTextpropertyfor

eachbuttonontheform.

7. ClicktheStartDebuggingbuttonontheStandardtoolbartorunthe

program.

8. Clickthefirstbuttonontheform(Button1).



TheButton1_ClickeventprocedurechangestheTextpropertyforeach

controlintheControlscollection.Yourformlookslikethis:



9. ClicktheClosebuttonontheform.

Theprogramends.

NOTE

TheTextpropertychangesmadebytheprogramhavenotbeen

replicatedontheformwithintheDesigner.Changesmadeatruntime

donotchangetheprogram'scorepropertysettings.

10. ClicktheSaveAllbuttonontheStandardtoolbartosaveyourchanges.

Specifythec:\vb05sbs\chap12folderasthelocation.

Nowyou'rereadytotryadifferentexperimentwiththeControlscollection:

usingtheLeftpropertytomoveeachcontrolintheControlscollectiontothe

right.



UseaForEach…Nextlooptomovecontrols

1. Displaytheformagain,andthendouble-clickthesecondbuttonobject

(Button2).

2. TypethefollowingprogramcodeintheButton2_Clickeventprocedure:



ForEachctrlInControls

ctrl.Left=ctrl.Left+25

Next



Eachtimetheuserclicksthesecondbutton,thisForEach…Nextloop

stepsthroughtheobjectsintheControlscollectiononebyoneand

movesthem25pixelstotheright.(Tomoveobjects25pixelstothe

left,youwouldsubtract25instead.)Apixelisadevice-independent

measuringunitwithwhichyoucanpreciselyplaceobjectsonaform.

TIP

InVisualBasic6,younormallyusetwipsinsteadofpixelstospecify

measurements.

Asinthepreviouseventprocedureyoutyped,thectrlvariableisa

“stand-in”forthecurrentobjectinthecollectionandcontainsthesame

propertysettingsastheobjectitrepresents.Inthisloop,youadjustthe

Leftproperty,whichdeterminesanobject'spositionrelativetotheleft

sideoftheform.

3. ClicktheStartDebuggingbutton.

Theprogramruns,andthreebuttonsappearontheleftsideoftheform.

4. Clickthesecondbuttonseveraltimes.

Eachtimeyouclickthebutton,theobjectsontheformgraduallymove

totheright.Yourscreenlookslikethisafterfiveclicks:



5. ClicktheClosebuttonontheformtostoptheprogram.

6. ClicktheSaveAllbuttontosaveyourchanges.

Youwon'talwayswanttomovealltheobjectsonaformasagroup.With

VisualBasic,youcanprocesscollectionmembersindividually.Inthenext

exercise,you'lllearnhowtokeepthethirdbuttonobjectinoneplacewhile

theothertwobuttonsmovetotheright.



UsingtheNamePropertyinaForEach…NextLoop

Ifyouwanttoprocessoneormoremembersofacollectiondifferentlythan

youprocesstheothers,youcanusetheNameproperty,whichuniquely

identifieseachobjectontheform.You'vesettheNamepropertyperiodically

inthisbooktomakeyourprogramcodemorereadable,butNamealsocan

beusedprogrammaticallytoidentifyspecificobjectsinyourprogram.

TousetheNamepropertyprogrammatically,singleouttheobjectstowhich

youwanttogivespecialtreatment,andthennotetheirNameproperties.

ThenasyouloopthroughtheobjectsontheformbyusingaForEach…

Nextloop,youcanuseoneormoreIfstatementstotestfortheimportant

Namepropertiesandhandlethoseobjectsdifferently.Forexample,let'ssay

youwanttoconstructaForEach…Nextloopthatmovesoneobjectmore

slowlyacrosstheformthantheotherobjects.YoucoulduseanIf…Then

statementtospottheNamepropertyoftheslowerobjectandthenmovethat



objectashorterdistance,bynotincrementingitsLeftpropertyasmuchas

thoseoftheotherobjects.

TIP

IfyouplantogiveseveralobjectsspecialtreatmentinaForEach…Next

loop,youcanuseElseIfstatementswiththeIf…Thenstatement,oryoucan

useaSelectCasedecisionstructure.

Inthefollowingexercise,you'lltesttheNamepropertyofthethirdbutton

object(btnMoveObjects)togivethatbuttonspecialtreatmentinaFor

Each…Nextloop.Theresultwillbeaneventprocedurethatmovesthetop

twobuttonstotherightbutkeepsthebottombuttonstationary.

TIP

InadditiontotheNameproperty,mostobjectssupporttheTagproperty.

SimilartotheNameproperty,theTagpropertyisalocationinwhichyoucan

storestringdataabouttheobject.TheTagpropertyisemptybydefault,but

youcanassigninformationtoitandtestittouniquelyidentifyobjectsin

yourprogramthatyouwanttoprocessdifferently.



UsetheNamepropertytogiveanobjectintheControlscollection

specialtreatment

1. Displaytheform,andthendouble-clickthethirdbuttonobject.

ThebtnMoveObjects_ClickeventprocedureappearsintheCodeEditor.

RememberthatyouchangedtheNamepropertyofthisobjectfrom

“Button1”to“btnMoveObjects”inanearlierexercise.

2. Typethefollowingprogramcodeintheeventprocedure:



ForEachctrlInControls

Ifctrl.Name<>"btnMoveObjects"Then

ctrl.Left=ctrl.Left+25



EndIf

Next



ThenewfeatureofthisForEach…NextloopistheIf…Thenstatement

thatcheckseachcollectionmembertoseewhetherithasaName

propertycalled“btnMoveObjects”.Iftheloopencountersthismarker,it

passesovertheobjectwithoutmovingit.Notethat,asintheprevious

examples,thectrlvariablewasdeclaredatthetopoftheformasa

variableoftheControltypewithscopethroughouttheform.

3. ClicktheSaveAllbuttontosaveyouredits.

TIP

ThecompleteControlsCollectionprogramislocatedinthe

c:\vb05sbs\chap12\controlscollectionfolder.

4. ClicktheStartDebuggingbutton.

Theprogramruns,andthethreebuttonobjectsappearontheform.

5. Clickthethirdbuttonobjectsixorseventimes.

Asyouclickthebutton,thetoptwobuttonobjectsmoveacrossthe

screen.Thethirdbuttonstaysinthesameplace,however,asshown

here:



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 12: Working with Collections and the System.Collections Namespace

Tải bản đầy đủ ngay(0 tr)

×