Tải bản đầy đủ - 0 (trang)
Chapter 7. Managing Data Tools and Data Binding

Chapter 7. Managing Data Tools and Data Binding

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

Introduction

VisualStudio2005includesanumberofnewcontrolsinthe

Toolboxthatyouneedtounderstandandlearntoleverageif

youexpecttobeabletocreateprofessionalapplications.Of

course,theToolboxisstuffedfullofcontrolsandwizardlaunchersthatfolksnewtoVisualStudioarealsogoingtohave

tolearn.It'swellbeyondthescopeofthisbooktodetailthem

all,butthereareanumberofdatamanagementcontrolsthatI

wouldliketodiscussinthischapter.Whenusedcorrectly,some

ofthese"data"controlscansaveyouagreatdealoftimewhen

buildingyourapplication,andtheycanalsobeusedas

foundationsforyourowncustomcontrols.Thatis,youcanuse

VisualStudiotocreateyourowncustomcompositecontrols

thatinheritfromtheexistingcontrols.Thiswayyoucanadd

eventsandproperties,andinterrelatetwoormorecontrolsinto

asinglecustomcontrol.

Asusual,theVisualStudioteamhasreinventedtoomanyof

thesecontrolsformyliking.Long-timerstellastoryaboutnew

developersatMicrosoft.Oneofthefirsttasksthese"kids"take

onistowriteanewdatagridcontrol.Asaresult,Microsoftis

hip-deepindatagridsofeveryconceivabletypeandsomeare

virtuallyinconceivable.Apparently,thebestoftheseisdubbed

thenewVisualStudiodatagridcontroleachtimeMicrosoft

shipsanewversion.Thistime,it'stheDataGridView.I'lldiscuss

thiscontroltosomeextentandwalkthroughsomeofitsnew

featuresandissues.Yup,ithaslotsofshinynewknobs,lights,

andswitches,buthowmanytimescanMicrosoftre-createthe

shovel?

Controlsandhowthey'reacceptedbythedeveloperandthirdpartycommunityarecriticallyimportanttoVisualStudioBill

Gatesthoughtso,andsodoI.TheveryfirstversionofVisual

BasicwasheldbackbyBill(theotherone)astheMicrosoft

developmentteamdidnotinclude"extensibility."Thatis,he



wantedVisualBasicprogrammerstobeabletobuythird-party

controlstoextendthepowerofVisualBasicapplicationsthey

wrote.Ithinkthiswasacriticallyimportantdecisionandmade

thedifferenceinhowquicklyVisualBasichasbeenadopted

overthelastdecade.Withoutthesethird-partygrids,custom

dialogs,andothercontrolsMicrosoftwasunableorunwillingto

createandsupport,VisualBasicdeveloperswouldhavebeen

stuckwiththefunctionallychallengedcontrolsthatshippedwith

VisualBasic.Thisextensiblearchitecturealsounloadedthe

MicrosoftVisualBasicteamsotheywerenotpressuredto

createandsupportahostofworld-classcontrols.Giventheir

limitedmanpowerandbudget,Microsoftknewthatthird-party

developerscouldspendalotmoretimeandtalentoncontrol

developmentthantheycould.Theresultwasthebirthofan

entireindustryofcontrolvendors.



IMHO

RememberthatVisualStudioisanapplicationdevelopment

platformandisdesignedtobuildanumberofdifferenttypesof

applicationarchitectures.Yes,boththeWindowsFormsand

ASP.NETarchitecturessupportuseofVisualStudioToolbox

controlstopopulateyourUI.However,thesetwoarchitectures

areradicallydifferent,soit'sunreasonabletoexpectthemto

behavethesameorsupportthesamefunctionalityatanylevel.

Anysimilarityisanaccidentalblessing.



ToleverageVisualStudio'sapplicationarchitectureflexibility

andextensibility,severalthird-partycompanieshavebuilt

controlstousewithWindowsFormsandASP.NETapplication

architectures.Someofthesecontrolsaredistributedasfree

samples(liketheterrificWindowsFormsValidatorcontrols

writtenbyBillHollis[1]thatareincludedontheDVD).Others



thatIhaveworkedwithorseendemonstratedfromtimeto

timearedistributedbycompanieslikeComponentSource[2],

(DanAppleman's)Desaware,Apex,VideoSoft,andDundas[3].In

anycase,Irecommendthatyounottrytolaunchany

substantiveprojectwithoutfirstspendingafewdaysexploring

thelibraryofcontrolsalreadyavailableintheindustry.Sure,

someofthesecontrolscancost$50or$1,000,butifyoufactor

inthecosttoduplicateeven50%oftheirfunctionality,most

arewellworththeone-timecost.Payspecialattentionto

controlsthatsupplythesourcecode.Thismakesthemfar

simplertoextendtoyourspecialneeds.

[1]Seewww.dotnetmasters.com.Lookunder"Samples".



[2]Seewww.componentsource.com/andwww.desaware.com/index.aspx.



[3]TheDVDincludesfreesamplesofmostofthiscompany'swares.



However,thischapterismorethanatouroftheVisualStudio

Toolbox.ItintroducesanewconcepttoVisualStudio

developersthestronglytypedTableAdapter.Asyou'llquickly

discover,Ithinkthisnewtechnologyhasitsplaceinsome

applicationsbutisnotauniversallyapplicabledataparadigm.

Petercallsthisthe"over-hyped"adapterIthinkyou'llseewhy

he(andI)feelsthiswayasyouprogressthroughthesepages.







TouringtheVisualStudioToolbox

VisualStudio2005'sToolboxisafarcryfromtheskimpytools

thatshippedwithVisualBasic1.0backin1991[4].Itincludesa

numberofnewcontrols,refinementsofexistingcontrols,and

replacementsforothers.Youmightalsobedisappointed(asI

am)thatsomecontrolsandwizard-launchersaremissingfrom

theToolbox.Forexample,theshortcutstotheDataAdapter

ConfigurationWizardandotherADO.NETdataaccesselements

havebeenshelved.Inaminute,I'llshowyouhowtore-enable

thesedeprecateddataaccesscontrols.

[4]YoumightfindBillyHollis'sHistoryofBasicanentertainingoverviewofhowIgothere.



Bythistime,theVisualStudio2005Toolbox(showninFigure

7.1)shouldbefamiliartoVisualBasicorC#developers.I've

explodedtheDatatabtoexposethestandardsetofdatacentriccontrols.NotablymissingfromtheDatatabarethe

mainstayDataAdapterandotherADO.NETcontrolswealluse

sooften.It'snothardtobringbackthesecontrols,asI'llshow

younext.



Figure7.1.TheVisualStudio2005Windows

FormsToolbox.



ExposingDeprecatedDataAccessControls

Microsoftseemstohavetakenamoralizingstanceonsomeof

thenewdataaccessfeatures.Forreasonsonlythey

understand,theyhavechosento"hide"someVisualStudio

featuresthatmanyofyouhavebeenusingfromthebeginning.

Forexample,everysingleADO.NETbook,article,orcourse

discusseshowtocreateanupdateableDataSetwiththe

DataAdapterConfigurationwizard(theDACW).AsIsaid,you

won'tfindthiswizardintheVisualStudio2005Toolbox.The

"Command"and"Connection"wizardiconsforeachofthe

providersaregone,tooliketheSqlCommandandSqlConnection

wizardlaunchers.

Thankfully,thisfunctionalityisstillinVisualStudio(fornow).I



expectthey'vebeenhiddenbecauseMicrosoftdoesn'twantyou

tousethemorcutyourselfwhilerunningwithscissors.Ialso

expecttheywantdeveloperstousethenewDataSource

ConfigurationwizardandstronglytypedDataSetobjects.These

deprecateditemsintheToolboxgenerateduntypedDataSet

objects.Manyofusstillfindanumberofgoodwaystouse

theseproductivityaidsespeciallywhenteachingfolkshowtouse

ADO.NET.Yes,Iexpecttherearestilllotsofmainstream

developerswhostilldependonthemandwillmissthemassoon

astheystartusingVisualStudio2005.

Thankfully,it'snothardtoaddthesehiddencontrolsandwizard

shortcutsbacktotheToolbarjustfollowthesesteps:

1. StartVisualStudioandcreateaWindowsFormsproject.

Sure,thiscanbedoneinanylanguageevenC#.

2. PindowntheToolboxtab,asyou'regoingtocreateanew

tab.

3. Right-clickbelowtheitemsintheToolboxandclick"Add

Tab".Giveyournewtabameaningfulname,like

"DeprecatedDataComponentsThatMicrosoftDoesn'tWant

MetoUse"orperhapssomethingshorter,like"Untyped

Data".

4. Right-clickagaininyournewtabandselect"Choose

Items...".Thisexposesthe"ChooseToolboxItems"dialog

(afteralongwaitwhileit'sinitialized).

5. Scrolldowntothesectionforyourdataaccessprovider.For

SQLServer,you'llwanttoadditemsfromthelistof

SqlClientcomponents.Ifyoutype"S",thepointermoves

promptlytothefirst"S".Youcanalsoenter"SqlClient"in

theFilterdialogtolocateallmatchingcomponents,as

showninFigure7.2.



Figure7.2.TheChooseToolboxItemsselector

dialog.

[Viewfullsizeimage]



6. RepeatthisprocessforanyODBCandOLEDBcomponents

thatyouwanttoexposeintheToolbar.Whenyou'redone,

youshouldhaveanewToolboxtabwiththeADO.NET

componentsyou'veusedforthelastthreeversions(as

showninFigure7.3).



Figure7.3.TheToolboxwiththemissing

ADO.NET1.1componentsreplaced.



Unfortunately,notalloftheproductivityfeaturesweallgot

usedtoinearlierversionsofVisualStudioarepresentinVisual

Studio2005andcan'tbeaddedback.Forexample,whenyou

wanttocreateaquickcalltoastoredprocedureandbuildthe

Parameterscollection,youcan(inVisualStudio2003)draga

storedprocedurefromtheServerExplorertotheForm,and

VisualStudiotakescareoftherest.Sadly,thisdoesnotworkin

the2005version.Iunderstandthatoneofthenewthird-party

refactoringadd-inscanbuildaParameterscollectionfroma

storedprocedure,soallhopeisnotlost.



FindingtheRightControl



Oneoftheproblemswithhavingsomanycontrolsinthe

Toolboxistryingtofindtheoneyouwant.VisualStudiodoesn't

helpmuchwhenitcomestolocatingaspecificcontrol,asit

supportsonlyascendingordescendingalphabeticsorting.

However,Ifinditeasiesttosimplycreateyourown"MFU"

(mostfrequentlyused)tabasyouchoosecontrolsforyour

project,simplydragthecontroltoyourownMFUtabwiththe

Ctrlkeyhelddown(tocopytheshortcut).Next,usethe"Move

Up"right-clickoptiontomoveyourcustomlisttothetopofthe

Toolbox,orsimplydragitthere.

BeforeyoucanaccesstheToolbox,you'llneedtoopenaForm

window.



UnderstandingtheToolTray

Someofthecontrolsyou'llfindintheToolboxaresimplyUI

elementsthatexposeagraphicontheWindows(orASP)Form,

aswellasproperties,methods,andevents.Othersare

shortcutsthatlaunchawizard(liketheDACWshortcutI

exposedintheprevioussection).Asyouwellknow,toadd

thesecontrolstoyourproject,youeitherdragthemtotheForm

ordouble-clickthemintheToolbox.Thisoperationinstructs

VisualStudiotogeneratecodeinFormx.designer.vb/cs.For

most(butnotall)controls,avisualUIelementisplacedonthe

form.FortheshortcutsandcontrolsthathavenoUIelements

(suchastheTimer,BindingNavigator,andthedataaccess

wizards),VisualStudioplacesaniconintheForm'sToolTray

(belowtheFormlayoutarea,asshowninFigure7.4).Theicons

arealsousedtosetthepropertiesofthecontrolsorrestartthe

wizardthatplacedthemintheToolTray.Deletingtheicon

removestheprojectcodegeneratedtosupportthem.However,



it'salwaysagoodideatounderstandtheintercontrol

relationshipsbeforedeletinganycross-dependentcontrol.



Figure7.4.TheForm'sToolTraypopulatedwith

severalcontrols.



Tip

Youcanbackoutsomedrag-and-dropoperationsbydeleting

selectedToolTrayicons.



AllthisisbasicallyunchangedfromearlierversionsofVisual

Studio,solet'sgettothenewstuff.







UsingtheDataSetToolboxElement

WhiletheDataSetclassisnotnewforVisualStudio,the

DataSetelementintheToolboxisnew.TheDataSetToolbox

elementlaunchesyetanotherwizardinthiscase,itgivesyou

twofundamentallydifferentwaystobuildorreferencea

DataSet,asshowninFigure7.5.



Figure7.5.AddingaDataSettoaFormusingthe

DataSetToolboxelement.



[Viewfullsizeimage]



Ineithercase,thistechniqueisusedtoaddanXSD-based,

stronglytypedDataSetoruntypedSystem.Data.DataSet

DataSetinstancetoaFormorcustomcomponentwithout

generatingboundUIelements.OncetheDataSetisaddedto

yourform,itbecomespartoftheFormcodescope,soit

appearsinotherdialogsthatpermiteasierbinding(asyou'll

seelaterinthischapter).



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

Chapter 7. Managing Data Tools and Data Binding

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

×