Tutorial 10MasterDetailUsingSelectableMasterGridViewWithDetailsDataView.docx
《Tutorial 10MasterDetailUsingSelectableMasterGridViewWithDetailsDataView.docx》由会员分享,可在线阅读,更多相关《Tutorial 10MasterDetailUsingSelectableMasterGridViewWithDetailsDataView.docx(14页珍藏版)》请在冰豆网上搜索。
Tutorial10MasterDetailUsingSelectableMasterGridViewWithDetailsDataView
Tutorial10:
Master/DetailUsingaSelectableMasterGridViewwithaDetailsDetailView
ScottMitchell
June2006
DownloadtheASPNET_Data_Tutorial_10_VB.exesamplecode.
ContentsofTutorial10(VisualBasic)
Introduction
Step1:
CreatingaSelectableGridView
Step2:
DisplayingtheSelectedProduct'sDetailsinaDetailsView
Summary
Introduction
Intheprevioustutorialwesawhowtocreateamaster/detailreportusingtwowebpages:
a"master"webpage,fromwhichwedisplayedthelistofsuppliers;anda"details"webpagethatlistedthoseproductsprovidedbytheselectedsupplier.Thistwopagereportformatcanbecondensedintoonepage.ThistutorialwillhaveaGridViewwhoserowsincludethenameandpriceofeachproductalongwithaSelectbutton.ClickingtheSelectbuttonforaparticularproductwillcauseitsfulldetailstobedisplayedinaDetailsViewcontrolonthesamepage.
Figure1.ClickingtheSelectButtonDisplaystheProduct'sDetails
Step1:
CreatingaSelectableGridView
Recallthatinthetwo-pagemaster/detailreportthateachmasterrecordincludedahyperlinkthat,whenclicked,senttheusertothedetailspagepassingtheclickedrow'sSupplierIDvalueinthequerystring.SuchahyperlinkwasaddedtoeachGridViewrowusingaHyperLinkField.Forthesinglepagemaster/detailsreport,wewillneedaButtonforeachGridViewrowthat,whenclicked,showsthedetails.TheGridViewcontrolcanbeconfiguredtoincludeaSelectbuttonforeachrowthatcausesapostbackandmarksthatrowastheGridView'sSelectedRow.
StartbyaddingaGridViewcontroltotheDetailsBySelecting.aspxpageintheFilteringfolder,settingitsIDpropertytoProductsGrid.Next,addanewObjectDataSourcenamedAllProductsDataSourcethatinvokestheProductsBLLclass'sGetProducts()method.
Figure2.CreateanObjectDataSourceNamedAllProductsDataSource
Figure3.UsetheProductsBLLClass
Figure4.ConfiguretheObjectDataSourcetoInvoketheGetProducts()Method
EdittheGridView'sfieldsremovingallbuttheProductNameandUnitPriceBoundFields.Also,feelfreetocustomizetheseBoundFieldsasneeded,suchasformattingtheUnitPriceBoundFieldasacurrencyandchangingtheHeaderTextpropertiesoftheBoundFields.Thesestepscanbeaccomplishedgraphically,byclickingtheEditColumnslinkfromtheGridView'ssmarttag,orbymanuallyconfiguringthedeclarativesyntax.
Figure5.RemoveAllButtheProductNameandUnitPriceBoundFields
ThefinalmarkupfortheGridViewis:
GridViewID="ProductsGrid"runat="server"AutoGenerateColumns="False"DataKeyNames="ProductID"
DataSourceID="AllProductsDataSource"EnableViewState="False">
BoundFieldDataField="ProductName"HeaderText="Product"SortExpression="ProductName"/>
BoundFieldDataField="UnitPrice"DataFormatString="{0:
c}"HeaderText="UnitPrice"
HtmlEncode="False"SortExpression="UnitPrice"/>
GridView>
Next,weneedtomarktheGridViewasselectable,whichwilladdaSelectbuttontoeachrow.Toaccomplishthis,simplychecktheEnableSelectioncheckboxintheGridView'ssmarttag.
Figure6.MaketheGridView'sRowsSelectable
CheckingtheEnablingSelectionoptionaddsaCommandFieldtotheProductsGridGridViewwithitsShowSelectButtonpropertysettoTrue.ThisresultsinaSelectbuttonforeachrowoftheGridView,asFigure6illustrates.Bydefault,theSelectbuttonsarerenderedasLinkButtons,butyoucanuseButtonsorImageButtonsinsteadthroughtheCommandField'sButtonTypeproperty.
GridViewID="ProductsGrid"runat="server"AutoGenerateColumns="False"DataKeyNames="ProductID"
DataSourceID="AllProductsDataSource"EnableViewState="False">
CommandFieldShowSelectButton="True"/>
BoundFieldDataField="ProductName"HeaderText="Product"SortExpression="ProductName"/>
BoundFieldDataField="UnitPrice"DataFormatString="{0:
c}"HeaderText="UnitPrice"
HtmlEncode="False"SortExpression="UnitPrice"/>
GridView>
WhenaGridViewrow'sSelectbuttonisclickedapostbackensuesandtheGridView'sSelectedRowpropertyisupdated.InadditiontotheSelectedRowproperty,theGridViewprovidestheSelectedIndex,SelectedValue,andSelectedDataKeyproperties.TheSelectedIndexpropertyreturnstheindexoftheselectedrow,whereastheSelectedValueandSelectedDataKeypropertiesreturnvaluesbasedupontheGridView'sDataKeyNamesproperty.
TheDataKeyNamespropertyisusedtoassociateoneormoredatafieldvalueswitheachrowandiscommonlyusedtoattributeuniquelyidentifyinginformationfromtheunderlyingdatawitheachGridViewrow.TheSelectedValuepropertyreturnsthevalueofthefirstDataKeyNamesdatafieldfortheselectedrowwhereastheSelectedDataKeypropertyreturnstheselectedrow'sDataKeyobject,whichcontainsallofthevaluesforthespecifieddatakeyfieldsforthatrow.
TheDataKeyNamespropertyisautomaticallysettotheuniquely-identifyingdatafield(s)whenyoubindadatasourcetoaGridView,DetailsView,orFormViewthroughtheDesigner.Whilethispropertyhasbeensetforusautomaticallyintheprecedingtutorials,theexampleswouldhaveworkedwithouttheDataKeyNamespropertyspecified.However,fortheselectableGridViewinthistutorial,aswellasforfuturetutorialsinwhichwe'llbeexamininginserting,updating,anddeleting,theDataKeyNamespropertymustbesetproperly.TakeamomenttoensurethatyourGridView'sDataKeyNamespropertyissettoProductID.
Let'sviewourprogressthusfarthroughabrowser.NotethattheGridViewliststhenameandpriceforalloftheproductsalongwithaSelectLinkButton.ClickingtheSelectbuttoncausesapostback.InStep2we'llseehowtohaveaDetailsViewrespondtothispostbackbydisplayingthedetailsfortheselectedproduct.
Figure7.EachProductRowContainsaSelectLinkButton
HighlightingtheSelectedRow
TheProductsGridGridViewhasaSelectedRowStylepropertythatcanbeusedtodictatethevisualstylefortheselectedrow.Usedproperly,thiscanimprovetheuser'sexperiencebymoreclearlyshowingwhichrowoftheGridViewiscurrentlyselected.Forthistutorial,let'shavetheselectedrowbehighlightedwithayellowbackground.
Aswithourearliertutorials,let'sstrivetokeeptheaesthetic-relatedsettingsdefinedasCSSclasses.Therefore,createanewCSSclassinStyles.cssnamedSelectedRowStyle.
.SelectedRowStyle
{
background-color:
Yellow;
}
ToapplythisCSSclasstotheSelectedRowStylepropertyofallGridViewsinourtutorialseries,edittheGridView.skinSkinintheDataWebControlsThemetoincludetheSelectedRowStylesettingsasshownbelow:
GridViewrunat="server"CssClass="DataWebControlStyle">
GridView>
Withthisaddition,theselectedGridViewrowisnowhighlightedwithayellowbackgroundcolor.
Figure8.CustomizetheSelectedRow'sAppearanceUsingtheGridView'sSelectedRowStyleProperty
Step2:
DisplayingtheSelectedProduct'sDetailsinaDetailsView
WiththeProductsGridGridViewcomplete,allthatremainsistoaddaDetailsViewthatdisplaysinformationabouttheparticularproductselected.AddaDetailsViewcontrolabovetheGridViewandcreateanewObjectDataSourcenamedProductDetailsDataSource.SincewewantthisDetailsViewtodisplayparticularinformationabouttheselectedproduct,configuretheProductDetailsDataSourcetousetheProductsBLLclass'sGetProductByProductID(productID)method.
Figure9.InvoketheProductsBLLClass'sGetProductByProductID(productID)Method
HavetheproductIDparameter'svalueobtainedfromtheGridViewcontrol'sSelectedValueproperty.Aswediscussedearlier,theGridView'sSelectedValuepropertyreturnsthefirstdatakeyvaluefortheselectedrow.Therefore,it'simperativethattheGridView'sDataKeyNamespropertyissettoProductID,sothattheselectedrow'sProductIDvalueisreturnedbySelectedValue.
Figure10.SettheproductIDParametertotheGridView'sSelectedValueProperty
OncetheproductDetailsDataSourceObjectDataSourcehasbeenconfiguredcorrectlyandboundtotheDetailsView,thistutorialiscomplete!
Whenthepageisfirstvisitednorowisselected,sotheGridView'sSelectedValuepropertyreturnsNothing.SincetherearenoproductswithaNULLProductIDvalue,norecordsarereturnedbytheGetProductByProductID(productID)method,meaningthattheDetailsViewisn'tdisplayed(seeFigure11).UponclickingaGridViewrow'sSelectbutton,apostbackensuesandtheDetailsViewisrefreshed.ThistimetheGridView'sSelectedValuepropertyreturnstheProductIDoftheselectedrow,theGetProductByProductID(productID)methodreturnsaProductsDataTablewithinformationaboutthatparticularproduct,andtheDetailsViewshowsthesedetails(seeFigure12).
Figure11.WhenFirstVisited,OnlytheGridViewisDisplayed
Figure12.UponSelectingaRow,theProduct'sDetailsareDisplayed
Summary
Inthisandtheprecedingthreetutorialswe'veseenanumberoftechniquesfordisplayingmaster/detailreports.InthistutorialweexaminedusingaselectableGridViewtohousethemasterrecordsandaDetailsViewtodisplaydetailsabouttheselectedmasterrecordonthesamepage.Intheearliertutorialswelookedathowtodisplaymaster/detailsreportsusingDropDownListsanddisplayingmasterrecordsononewebpageanddetailrecordsonanother.
Thistutorialconcludesourexaminationofmaster/detailreports.Startingwiththenexttutorialwe'llbeginourexplo