Tải bản đầy đủ - 0 (trang)
Chapter 27. Building Rich, Data-Driven Web Applications

Chapter 27. Building Rich, Data-Driven Web Applications

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

IntroductiontoDataBindinginASP.NET

Databindingreferstotheactof"binding"userinterface

elementstounderlyingdatathroughsomemeans.Thischapter

doesnotfocusmuchonhowpreviousversionsofASP.NET

accomplisheddatabindingexcepttobrieflycompareand

contrast.AlthoughthenewASP.NETcontrolscanbeboundthe

"oldway"aswellasthenewASP2005way,youwillseeahuge

improvementinproductivitybywritingyourcodetotake

advantageofsomeofthenewfeatures.Thissectionintroduces

youtothedatasourcepatternthatexistsinbothASP2005and

WindowsFormsandhowtocreatedatasources.Finally,this

sectionwillfinishupwithanoverviewofthewidevarietyof

controlsavailabletoyouforusingas-isorforextendingthrough

inheritance.



TheDataSourceModel

Datasourcesarejustthat:sourcesofdata.Thenewdata

sourcemodelisdesignedinsuchawaythatyoucancreatea

datasourceforanytypeofunderlyingdata,andtheUIcontrol

canthenbindtothedatasourceandnotdirectlytothedata.

ThisallowstheUIcontroltofocussimplyonrenderingdataand

notontheunderlyingformatofthedata.Forexample,using

variousdatasourcesyoucannowbindasinglecontroltoan

XMLdocument,toaDataSet,toastronglytypedcollectionof

objects,totheresultsofastoredprocedureexecutioninSQL,

ortotheresultsofanOLEDBquery,andmuchmore.

Thestepsrequiredtoconnectyourcontrolstoadatasourceare

extremelysimple.First,youcreateyourdatasource(discussed

shortly),andthenyoudragabindablecontrolontotheform,

selectthedatasourcefromthedrop-downbox,andyou'rewell

onyourwaytocreatingarich,interactive,anddata-drivenweb



page.



CreatingDataSources

Creatingadatasourceisasimpletask.Afteryou'vecreatedan

emptywebsitethroughVisualStudio2005,createanewWeb

Form.Tocreateadatasource,youdragoneofthefivebuilt-in

datasourcecomponentsontoyourform.Thefollowingisabrief

descriptionofthedatasourcecomponentsthatcomewith

ASP.NET:

SqlDataSourceAdatasourceusedtoaccessdatacontainedin



aSQLServer2000(orhigher,includingSQL2005)

database.

AccessDataSourceAdatasourceusedtoconnecttodata



containedinaMicrosoftAccess(.mdb)file.

ObjectDataSourceAnextremelypowerfuldatasource



componentthatallowsyoutoconnectaUIcontroltoan

arbitraryobject.

XmlDataSourceAdatasourceusedtoconnecttodata



containedwithinanXMLdocument.

SiteMapDataSourceAdatasourcedesignedtoconnecttothe



datarepresentingasitemap.

Afteryoudragthedatasourceontotheform,theDataSource

ConfigurationWizarddialogwillappear.Thiswizardwillwalk

youthroughtheprocessofconfiguringalltheaspectsofyour

datasource.Thisincludesspecifyingthequerythatobtainsthe

dataaswellasadditionalqueries(orstoredprocedures,if

applicable)usedforCreate,Update,andDeleteoperations.



Withthoseoperationsdefined,youcanthenusethestock

ASP.NETcontrolstocreate,retrieve,update,anddeletedata

fromyourdatasourcewhetherthedataisinanXMLfile,aSQL

database,anAccessdatabase,oraninstanceofanobject

withinyourapplication.

Toseethisinaction,opentheToolboxpanelinVisualStudio

anddraganAccessDataSourcecomponentontoyourform.This

shouldautomaticallybringupthesmarttagmenu.Fromhere,

clicktheConfigureDataSourceoption.Thiswillbringupa

screenaskingyouforthefilenameoftheAccessdatabaseto

whichthedatasourcewillattach.Browsetothelocationofyour

Northwind.mdbfile(thisfileisincludedwithVisualStudio2005in

oneofthesampledirectories)andclickNext,bringingupthe

screenshowninFigure27.1.



Figure27.1.SELECTstatementconfigurationfor

anAccessdatasource.



[Viewfullsizeimage]



Selecteachcolumnspecifically(insteadofclickingtheasterisk)

andthenclickNexttomovetothenextstepinthewizard.The

nextstepallowsyoutoclickTestQuerytoseeapreviewofthe

datathatwillbeappearinginthecontrol.Afteryou'vetested

thequery,clickFinishandtheDataSourceConfigurationWizard

willfinish.

DragaGridViewcontrolontotheform,autoformatithoweveryou

like,andsetthedatasourcetotheAccessdatasourceyoujust

created(namedAccessDataSource1bydefault).Whenyourunthis

pageindebug,youwillseeoutputthatlookslikeFigure27.2.



Figure27.2.AGridViewconnectedtoanAccess

datasource.



[Viewfullsizeimage]



Thisisgreat,butitonlyallowsyoutoviewthedata.The

GridViewalsoallowsyoutoupdateanddeleteexistingrows.The

greatthingaboutdatasourcesisthattheCreate,Retrieve,

Update,andDeletecommandsareallstoredinthedatasource,

andthecontrolneednothaveanyknowledgeofthose

commands.Toconfigureyourdatasourceforinsert,update,

anddeleteoperations,gobacktotheConfigureDataSource

Wizardandclick"Next"togettothescreenwhereyouchoose

thecolumnsforyourSELECTstatement.ClicktheAdvanced

buttonandyouwillseethedialogshowninFigure27.3,which

asksifyouwanttoautogenerateUPDATE,DELETE,andINSERT

statements.



Figure27.3.Dialogpromptingtoautogenerate

UPDATE,DELETE,andINSERTstatements.



Beforeyouthinkthisisactuallygoingtowork,gointothe

propertiesforthedatasourceandtakealookattheInsertQuery,

UpdateQuery,andDeleteQueryproperties.Thereisanextremely

usefulminiaturequerybuilderthatwillpopupwhenyouopen

theseproperties.Moreoftenthannot,autogeneratedqueries

areeithernotefficientenoughorsimplydon'tworkatall.

However,theyareagoodstartingpointforyoutogoinand

optimizethemtoworkproperly.Afterasmalltweaktomakeit

workproperly,thescreenshotshowninFigure27.4showsa

functioningupdatequery.



Figure27.4.Afunctioningupdatequeryforan

AccessDatasource.



[Viewfullsizeimage]



TheonlythingthataGridViewcan'tdoisutilizetheInsertQuery

propertyofthedatasource.Thissectionwon'tgetintodetails

onhowtodothatbecausethesection"UsingData-Bound

Controls"laterinthischaptercoversutilizingthevarious

controlsthatcanbedata-bound.



Data-BoundControlHierarchy

AlmosteverysinglecontrolthatcomeswithASP.NET2.0canbe

involvedinthedata-bindingprocessinsomeway.However,

thereisasmallerlistofcontrolsthataredesignedspecifically

forworkinginadata-boundfashion,whetheritistodisplayand

editthedetailsofasinglerowofdataortodisplayandedit

multiplerowsinasorted,paged,orevenfilteredway.Thislist

isshowninFigure27.5.



Figure27.5.Hierarchyofcontrolsthatsupport

databinding.



[Viewfullsizeimage]



Thefollowingisabriefoverviewofthecontrolsshowninthe

hierarchyinFigure27.5.Thenextsectionofthischapterwill

showyouhowtouseeachofthesecontrols.

AdRotatorAstandardcontrolforrotatingadvertisement



informationfromadata-boundsource

ListBoxAstandardlistboxcontrolthatdisplaysmultiple



elementsatatime,andcanallowsingleormultiple

selectionofitems

CheckBoxListAlistofcheckboxesthatcanberenderedin



severalmodesfromadatasource

DropDownListAtraditional"combobox"-stylecontrolwhose



elementsandcurrentlyselecteditemcanbepulledfroma

datasource

RadioButtonListAlistofradiobuttonsthatcanberenderedin



severalmodesfromadatasource

DetailsViewAcompositecontrolthatcanrenderadetailview



showingthecolumnsandvaluesforaspecificdatarow

FormViewAcompositecontrolthatrendersaninteractiveform



populatedbyadatasource

GridViewAgrid-styleviewofdatafromadatasourcethatis



extremelypowerfulandcansupportin-lineeditanddeletion

ofdata



UsingData-BoundControls

Manycontrolssupportbinding,butthankstotheuseofthe

datasourcemodel,manyofthesimplercontrolsareselfexplanatoryandeasytoworkwith,suchastheCheckBoxListand

theListBox.Thissectioncoverssomeofthemorepowerful

controlsandgivesyouanintroductiontotheiruse.Foramore

thoroughexaminationofallASP.NET2.0controls,youshould

considerreadingoneofthebooksthatarespecifictoASP.NET

2.0,suchasASP2005Unleashed,fromSamsPublishing(ISBN:

0672328232).



UsingtheGridViewControl

EarlierinthischapteryousawabriefintroductiontotheGridView

control.Thiscontrolisresponsibleforrenderingalistofitems

inagridformat,andcanbeconfiguredtoallowforinline

editinganddeletingofexistingrowsifthedatasourcetowhich

thecontrolisconnectedhasaDeleteCommandandanUpdateCommand

defined.IfyousettheAutoGenerateDeleteButton,

AutoGenerateEditButton,andAutoGenerateSelectButtonproperties,the

manualtaskspreviouslyrequiredoftheDataGridinASP.NET

1.1willbetakencareof.Infact,youwon'thavetowriteanyof

yourownupdatecodebecausethedatasourcewillperformthe

update(ordelete)attherequestoftheGridView.



UsingtheDetailsViewControl

TheDetailsViewcontrolisusedfordisplayingthedetailsfora

singlerowofdata.Mostoftenwhenauserinterfacecallsfor

thedisplayofmultiplerowsofdatainagridformat,thesame

interfacerequiresthatarow'sdetailseventuallybedisplayed,



eitheronthesamepageoronadifferentpage.

Ifyou'vebeenfollowingalong,dragaDetailsViewcontrolonto

theformandsetitsdatasourcetothesameastheGridView,

AccessDatasource1.MakesuretosettheEnablePagingpropertyto

true.TheonethingtokeepinmindthatistotheDetailsView

control,onerowisequivalenttoonepage.Therefore,tosetthe

rowbeingviewedoredited,yousimplysetthePageIndex

property.

WithbothaGridViewandaDetailsViewonthesamepage,you

mightassumethatifyouclicktheSelectbuttonontheGridView

(thisbuttonappearswhenyourGridViewallowsrowselection),

theDetailsViewwillautomaticallymovetotheselectedrow.This

wouldbetrueifthedatasourcesupportedthenotionof

currency(maintainingcurrentrowinstate),butASP.NET2.0

datasourcesdonotsupportcurrency,withgoodreason.To

makeaGridViewandaDetailsViewsyncupwhentheuserselects

arowintheGridView,allyouhavetodoisaddthefollowing

lineofcodetotheGridView'sSelectedIndexChangedeventhandler:

DetailsView1.PageIndex=GridView1.SelectedIndex;



Ifyou'refamiliarwithASP.NET1.1programming,youare

probablywonderingwherethecalltoDataBind()isforthe

DetailsView.ThereisnoneedbecauseallnewASP.NET2.0

controlsthatsupportdatabindingindicatetotheASP.NET

frameworkwhetherornotsomethinghaschangedwiththe

controlthatrequiresittorebind.ThisfacetofASP.NETsavesa

lotoftimeandeffortonbehalfoftheprogrammer,whono

longerhastowritecomplicatedcodetodeterminewhether

bindingneedstotakeplaceorcreateconvolutedworkarounds

toavoiddouble-bindingthesamedata.



UsingtheFormViewControl



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

Chapter 27. Building Rich, Data-Driven Web Applications

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

×