Tải bản đầy đủ - 0 (trang)
Advanced ADO.NET Data Binding: Looking Behind the Scenes

Advanced ADO.NET Data Binding: Looking Behind the Scenes

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

keepstrackofthecurrencyofthedatasource.Ifyoubindalist

toacontrolthatdisplaysasingledatum,thecontrolwilldisplay

thecurrentitemasdeterminedbythecurrencymanager.

(Becausewe'llalmostalwaysbetalkingaboutbindingtolist

datasources,weusebindingmanagerandcurrencymanager

interchangeablythroughout.)

Mostofthetime,eachbindingsourcehasexactlyonecurrency

managerassociatedwithit;twocontrolsboundtothesame

bindingsourceshareacurrencymanagerand,therefore,share

currency.Intheeventthatyouwanttohavetwocontrols

boundtoasinglebindingsource,butwithdifferentcurrency,

eachcontrolneedstohaveitsownbindingcontext.Abinding

contextisacollectionthatkeepstrackofpairsofbinding

sourcesandbindingmanagers.Withineachcontext,every

bindingsourcehasauniquebindingmanager,buttwocontexts

canassociatedifferentmanagerswiththesamesource,thereby

keepingtwoormorecurrenciesinonebindingsource.

Intypicalscenarios,thereisonlyonebindingcontext,sothis

pointislargelymoot.Evenwhenyouhaveonlyone,thebinding

contextdoeshaveoneuse:Incomplex-data-binding,the

bindingcontextexposedbyalistobjectletsyouobtainthe

currencymanagerforthebindingsource.



Binding-RelatedExtensionstoHostItemsand

HostControls

Alldata-bindablehostitemsandhostcontrolsallowyoutobind

anysingledatumtoanywritableproperty.Theseobjects

implementIBindableComponent,whichdefinestwoproperties:

PropertyBindingContextAsBindingContext



ReadOnlyPropertyDataBindingsAsControlBindings-Collection



Typically,youwillhaveonlyonebindingcontext.Shouldyou

needtohavetwocontrolsboundtothesamelistdatasource,

butwithdifferentcurrencyforeach,youcancreatenewbinding

contextsandassignthemtothecontrolsasyouwant.Each

hostitemandhostcontrolwillraiseaBindingContextChanged

eventifyoudo.

TheControlBindingsCollectionobjecthasmanymethodsfor

addingandremovingbindingobjects;thereisonebindingfor

eachboundpropertyonthecontrol.Italsohasaread-only

indexerthatmapsthenameofapropertytoitsbindingobject.

ThelistobjectaggregateinExcelhasalargenumberofnew

properties,methods,andeventsaddedontosupportcomplex

databinding.Wedescribedtheviewextensionsearlier;now

thatwehavecoveredhowdatabindingworks,wecandiscuss

thedatamodelextensions.



NewData-RelatedListObjectHostControl

PropertiesandMethods



ThetwomostimportantpropertiesontheListObjecthost

controldeterminewhatdatasourceisactuallycomplex-databoundtothecontrol:

PublicPropertyDataSourceAsObject

PublicPropertyDataMemberAsString



Thereasonthatthelistobjectdividesthisinformationintotwo

propertiesisbecausesomedatasourcescontainmultiplelists,

calledmembers.YoucouldsettheDataSourcepropertytoa

dataset,forexample,andtheDataMemberpropertytothe

nameofadatatablecontainedbythedataset.

Thepropertiescanbesetinanyorder,andbindingwillnot

commenceuntilbotharesettosensiblevalues.Itusuallyis

easier,however,touseoneoftheSetDataBindingmethodsto

setbothpropertiesatthesametime:

PublicSubSetDataBinding(ByValdataSourceAsObject)

PublicSubSetDataBinding(ByValdataSourceAsObject,_

ByValdataMemberAsString)

PublicSubSetDataBinding(ByValdataSourceAsObject,_

ByValdataMemberAsString,_

ByValParamArraymappedColumnsAsString())



Noticethatinthelastoverload,youcanspecifywhichcolumns

inthedatatablearetobebound.Doingsoprovesquitehandy

ifyouhavealarge,complicatedtablethatyouwanttodisplay

onlyaportionof,orifyouwanttochangetheorderinwhich

thecolumnsdisplay.

Insomecases,thedatasourceneedsnofurtherqualificationby

adatamember,soyoucanleaveitblank.Inthepreceding

example,thedesignerautomaticallygeneratescodethat



createsaBindingSourceproxyobject,whichneedsnofurther

qualification.Thegeneratedcodelookssomethinglikethecode

inListing17.7.



Listing17.7.SettinguptheBindingSource



Me.OrderBookBindingSource=NewSystem.Windows.Forms.BindingSource()

Me.OrderBookBindingSource.DataMember="Book"

Me.OrderBookBindingSource.DataSource=this.orderDataSet1

Me.BookList.SetDataBinding(Me.OrderBookBindingSource,"",

"Title","ISBN","Price")



Becausethebindingsourceknowswhattabletoproxy,thelist

objectneedsnofurtherqualification.



Note

UnliketheDataGridcontrol,thelistobjectdoesnot

allowyoutosettheboundcolumnsusingacolumn

chooserinthelistobject'sPropertiespane.Ifyou

haveadata-boundlistobjectinthedesigner,

however,youcansimplydeletecolumnsatdesign

time;VisualStudiowillupdatetheautomatically

generatedcodesothatthedeletedcolumnisno

longerboundwhenthecoderuns.



Theinformationaboutwhichcolumnsandtablesareboundto

whichlistobjectsispersistedinthedocument;youdonotneed

torebindthelistobjectsexplicitlyeverytimethecustomization

starts.Shouldyouwanttoensurethatallthepersisted

informationaboutthedatabindingsisclearedfromthe



document,youcancalltheResetPersistedBindingInformation

method:

PublicSubResetPersistedBindingInformation()



ThedatasourceofthelistobjectmustimplementeitherIListor

IList-Source.Shouldyoupassaninvalidobjectwhentryingto

setthedatasource,thelistobjectwillthrowa

SetDataBindingFailedException(asdescribedlaterinthis

chapter).

Youcancheckwhetherthedatasourceanddatamembershave

beensetproperlyandthelistobjectiscomplex-data-boundby

checkingtheIsBindingproperty:

PublicReadOnlyPropertyIsBindingAsBoolean



Complex-data-boundlistobjectskeepthecurrencytheselected

rowinthecurrencymanagerforthedatasourceinsyncwiththe

selectedrowinthehost.Youcansetorgetthecurrencyofthe

datasource'sbindingmanagerwiththisproperty:

PublicPropertySelectedIndexAsInteger



Notethattheselectedindexis1-based,not0-based;1

indicatesthatnorowisselected.Whentheselectedindex

changes,thelistobjectraisestheSelectedIndexChangedevent.

ItraisesIndexOutOfRangeExceptionshouldyouattempttoset

aninvalidindex.

IftheAutoSelectRowspropertyissettoTRue,theview's

selectionisupdatedwheneverthecurrencychanges:



PublicPropertyAutoSelectRowsAsBoolean



Threeotherpropertiesdirectlyaffecttheappearanceofdataboundlistobjects:

PublicPropertyDataBoundFormatAsXlRangeAutoFormat

PublicPropertyDataBoundFormatSettingsAsFormatSettings

PublicPropertyAutoSetDataBoundColumnHeadersAsBoolean



TheDataBoundFormatpropertydetermineswhetherExceldoes

automaticreformattingofthelistobjectcellswhenthedata

change.Youhaveseveraldozenformatstochooseamong;the

defaultisxlRangeAutoFormatNone.Ifyouwantnoformatting,choose

xlRangeAutoFormatNone.Youcanalsochoosewhichaspectsofthe

formattingyouwanttoapplybysettingthebitflagsinthe

DataBoundFormatSettingsproperty(bydefault,alltheflagsare

turnedon):

PublicEnumFormatSettings

Alignment=256

Border=4096

Font=16

Number=1

Pattern=65536

Width=1048576

EndEnum



TheAutoSetDataBoundColumnHeaderspropertyindicates

whetherthelistobjectdatabindingshouldautomaticallycreate

aheaderrowinthelistobjectthatcontainsthecolumnnames.

ItissettoFalsebydefault.



NewData-RelatedListObjectEvents

Therearealsoseveralnewdata-relatedeventsontheList

Object,listedinTable17.1.

Table17.1.NewEventsAssociatedwithListObject

EventName



DelegateType



DataSourceChanged



EventHandler



DataMemberChanged



EventHandler



SelectedIndexChanged



EventHandler



DataBindingFailure



EventHandler



BeforeAddDataBoundRow



BeforeAddDataBoundRowEventHandler



ErrorAddDataBoundRow



ErrorAddDataBoundRowEventHandler



OriginalDataRestored



OriginalDataRestoredEventHandler



TheDataSourceandDataMemberpropertiesonthelistobject

aggregatedeterminetowhatdatasourcethelistobjectis

complex-data-bound.TheDataSourceChangedand

DataMemberChangedeventsareraisedwhenthecorresponding

propertiesarechanged.

TheSelectedIndexChangedeventisprimarilyaviewevent;

whentheuserclicksadifferentrow,theeventisraised.Note,

however,thatchangingtheselectedrowalsochangesthe

currencyofthebindingmanager.Thiscanbeusedto

implementmaster-detaileventbinding.



Ifforanyreasonanedittothelistobjectfailsifthedatabinding

layerattemptsunsuccessfullytoaddaroworcolumntothelist,

forexample,orifavaluetypedinthelistobjectcannotbe

copiedbackintothebounddatasourcetheDataBindingFailure

eventisraised.

TheBeforeAddDataBoundRoweventhastwoprimaryuses.

Listing17.8showsitsdelegate.



Listing17.8.TheBeforeAddDataBoundRowEvent

Types



PublicDelegateSubBeforeAddDataBoundRowEventHandler(_

ByValsenderAsObject,_

ByValeAsBeforeAddDataBoundRowEventArgs)

PublicNotInheritableClassBeforeAddDataBoundRowEventArgs

InheritsEventArgs

PublicPropertyCancelAsBoolean

PublicReadOnlyPropertyItemAsObject

EndClass



Theitempassedtotheeventhandleristherowthatisaboutto

beadded.Theeventcanbeusedeithertoedittherow

programmaticallyjustbeforeitisaddedortododatavalidation

andcanceltheadditionshouldthedatabesomehowinvalid.

AftertheBeforeAddDataBoundRoweventishandled,thelist

objectattemptstocommitthenewrowintothedatasource.If

thatoperationthrowsanexceptionforanyreason,thelist

objectdeletestheoffendingrow.Beforeitdoesso,however,it

givesyouonechancetofixtheproblembyraisingthe

ErrorAddDataBoundRowevent.Listing17.9showsitsdelegate.



Listing17.9.TheErrorAddDataBoundRowEvent



Types



PublicDelegateSubErrorAddDataBoundRowEventHandler(_

ByValsenderAsObject,_

ByValeAsErrorAddDataBoundRowEventArgs)

PublicNotInheritableClassErrorAddDataBoundRowEventArgs

InheritsEventArgs

PublicReadOnlyPropertyInnerExceptionAsException

PublicReadOnlyPropertyItemAsObject

PublicPropertyRetryAsBoolean

EndClass



Theexceptioniscopiedintotheeventarguments;thenthe

handlercananalyzetheexception,attempttopatchuptherow,

andretrythecommitoperation.Shoulditfailasecondtime,

therowisdeleted.Theexceptionthrowninthiscasemaybe

thenewSetDataBindingFailedException,whichisdocumented

below.

Adatasourcemayhaveafixednumberofrowsorafixed

numberofcolumns.Adatasourcecanalsocontainread-only

dataorread-onlycolumnnames.Therefore,attemptingtoedit

cells,addrows,removerows,addcolumns,orremovecolumns

canallfail.Inthesecases,thelistobjectdisallowsthechange

andrestorestheoriginalshape.Whenitdoesso,itraisesthe

OriginalDataRestoredevent.Listing17.10showsitsdelegate.



Listing17.10.TheOriginalDataRestoredEvent

Types



PublicDelegateSubOriginalDataRestoredEventHandler(_

ByValsenderAsObject,_

ByValeAsOriginalDataRestoredEventArgs)

PublicNotInheritableClassOriginalDataRestoredEventArgs



InheritsEventArgs

PublicReadOnlyPropertyChangeReasonAsChangeReason

PublicReadOnlyPropertyChangeTypeAsChangeType

EndClass

PublicEnumChangeType

ColumnAdded=1

ColumnHeaderRestored=5

ColumnRemoved=2

RangeValueRestored=0

RowAdded=3

RowRemoved=4

EndEnum

PublicEnumChangeReason

DataBoundColumnHeaderIsAutoSet=3

ErrorInCommit=4

FixedLengthDataSource=1

FixedNumberOfColumnsInDataBoundList=2

Other=5

ReadOnlyDataSource=0

EndEnum



NewException

Databindingcanfailundermanyscenarios;the

SetDataBindingFailedExceptionisthrowninthreeofthem:

Ifthedatasourceofthelistobjectisnotalistdatasource

Ifthedatasourceofthelistobjecthasnodata-bound

columns

Ifthelistobjectcannotberesizedwhenthedatachange

TheexceptionclasshasthesepublicmethodsandaReason

property,showninListing17.11.



Listing17.11.TheSetDataBindingFailedException



Types



PublicNotInheritableClassSetDataBindingFailedException

InheritsException

PublicSubNew()

PublicSubNew(ByValmessageAsString)

PublicSubNew(ByValmessageAsString,_

ByValinnerExceptionAsException)

PublicReadOnlyPropertyReasonAsFailureReason

EndClass

PublicEnumFailureReason

CouldNotResizeListObject=0

InvalidDataSource=1

NoDataBoundColumnsSpecified=2

EndEnum



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

Advanced ADO.NET Data Binding: Looking Behind the Scenes

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

×