Thistutorialispartofaset.FindoutmoreaboutdataaccesswithASP.NETintheWorkingwithDatain ASP.NET2.0sectionoftheASP.NETsiteathttp://www.asp.net/learn/dataaccess/default.aspx.
WorkingwithDatainASP.NET2.0::Displaying DataWiththeObjectDataSource Introduction
Withourapplicationarchitectureandwebsitepagelayoutcomplete,we'rereadytostartexploringhowto accomplishavarietyofcommondataandreportingrelatedtasks.Intheprevioustutorialswe'veseenhowto programmaticallybinddatafromtheDALandBLLtoadataWebcontrolinanASP.NETpage.Thissyntax assigningthedataWebcontrol'sDataSource propertytothedatatodisplayandthencallingthecontrol's DataBind() methodwasthepatternusedinASP.NET1.xapplications,andcancontinuetobeusedinyour 2.0applications.However,ASP.NET2.0'snewdatasourcecontrolsofferadeclarativewaytoworkwith data.UsingthesecontrolsyoucanbinddataretrievedfromtheBLLcreatedintheprevioustutorial without havingtowritealineofcode! ASP.NET2.0shipswithfivebuiltindatasourcecontrolsSqlDataSource,AccessDataSource, ObjectDataSource,XmlDataSource,andSiteMapDataSourcealthoughyoucanbuildyourown customdata sourcecontrols,ifneeded.Sincewehavedevelopedanarchitectureforourtutorialapplication,we'llbeusing theObjectDataSourceagainstourBLLclasses.
Figure1:ASP.NET2.0IncludesFiveBuiltInDataSourceControls TheObjectDataSourceservesasaproxyforworkingwithsomeotherobject.Toconfigurethe ObjectDataSourcewespecifythisunderlyingobjectandhowitsmethodsmaptotheObjectDataSource's Select,Insert,Update,andDelete methods.Oncethisunderlyingobjecthasbeenspecifiedandits methodsmappedtotheObjectDataSource's,wecanthenbindtheObjectDataSourcetoadataWebcontrol. ASP.NETshipswithmanydataWebcontrols,includingtheGridView,DetailsView,RadioButtonList,and DropDownList,amongothers.Duringthepagelifecycle,thedataWebcontrolmayneedtoaccessthedatait's boundto,whichitwillaccomplishbyinvokingitsObjectDataSource'sSelect methodifthedataWebcontrol
1of14
supportsinserting,updating,ordeleting,callsmaybemadetoitsObjectDataSource'sInsert,Update,or Delete methods.ThesecallsarethenroutedbytheObjectDataSourcetotheappropriateunderlyingobject's methodsasthefollowingdiagramillustrates.
Figure2:TheObjectDataSourceServesasaProxy WhiletheObjectDataSourcecanbeusedtoinvokemethodsforinserting,updating,ordeletingdata,let'sjust focusonreturningdatafuturetutorialswillexploreusingtheObjectDataSourceanddataWebcontrolsthat modifydata.
Step1:AddingandConfiguringthe ObjectDataSourceControl
StartbyopeningtheSimpleDisplay.aspx pageintheBasicReporting folder,switchtoDesignview,and thendraganObjectDataSourcecontrolfromtheToolboxontothepage'sdesignsurface.The ObjectDataSourceappearsasagrayboxonthedesignsurfacebecauseitdoesnotproduceanymarkupit simplyaccessesdatabyinvokingamethodfromaspecifiedobject.ThedatareturnedbyanObjectDataSource canbedisplayedbyadataWebcontrol,suchastheGridView,DetailsView,FormView,andsoon. Note:Alternatively,youmayfirstaddthedataWebcontroltothepageandthen,fromitssmarttag,choose the<Newdatasource>optionfromthedropdownlist. TospecifytheObjectDataSource'sunderlyingobjectandhowthatobject'smethodsmaptothe ObjectDataSource's,clickontheConfigureDataSourcelinkfromtheObjectDataSource'ssmarttag.
2of14
Figure3:ClicktheConfigureDataSourceLinkfromtheSmartTag ThisbringsuptheConfigureDataSourcewizard.First,wemustspecifytheobjecttheObjectDataSourceisto workwith.Ifthe"Showonlydatacomponents"checkboxischecked,thedropdownlistonthisscreenlists onlythoseobjectsthathavebeendecoratedwiththeDataObject attribute.Currentlyourlistincludesthe TableAdaptersintheTypedDataSetandtheBLLclasseswecreatedintheprevioustutorial.Ifyouforgotto addtheDataObject attributetotheBusinessLogicLayerclassesyouwon'tseetheminthislist.Inthatcase, uncheckthe"Showonlydatacomponents"checkboxtoviewallobjects,whichshouldincludetheBLLclasses (alongwiththeotherclassesintheTypedDataSettheDataTables,DataRows,andsoon). FromthisfirstscreenchoosetheProductsBLL classfromthedropdownlistandclickNext.
Figure4:SpecifytheObjecttoUsewiththeObjectDataSourceControl ThenextscreeninthewizardpromptsyoutoselectwhatmethodtheObjectDataSourceshouldinvoke.The dropdownliststhosemethodsthatreturndataintheobjectselectedfromthepreviousscreen.Herewesee GetProductsByProductID,GetProducts,GetProductsByCategoryID,andGetProductsBySupplierID. SelecttheGetProducts methodfromthedropdownlistandclickFinish(ifyouaddedthe DataObjectMethodAttribute totheProductBLL'smethodsasshownintheprevioustutorial,thisoption willbeselectedbydefault).
3of14
Figure5:ChoosetheMethodforReturningDatafromtheSELECTTab
ConfiguretheObjectDataSourceManually
TheObjectDataSource'sConfigureDataSourcewizardoffersaquickwaytospecifytheobjectitusesandto associatewhatmethodsoftheobjectareinvoked.Youcan,however,configuretheObjectDataSource throughitsproperties,eitherthroughthePropertieswindowordirectlyinthedeclarativemarkup.Simplyset theTypeName propertytothetypeoftheunderlyingobjecttobeused,andtheSelectMethod tothemethod toinvokewhenretrievingdata.
<asp:ObjectDataSourceID="ObjectDataSource1"runat="server" SelectMethod="GetProducts" TypeName="ProductsBLL"> </asp:ObjectDataSource>
EvenifyouprefertheConfigureDataSourcewizardtheremaybetimeswhenyouneedtomanuallyconfigure theObjectDataSource,asthewizardonlylistsdevelopercreatedclasses.Ifyouwanttobindthe ObjectDataSourcetoaclassinthe.NETFrameworksuchastheMembershipclass,toaccessuseraccount information,ortheDirectoryclasstoworkwithfilesysteminformationyou'llneedtomanuallysetthe ObjectDataSource'sproperties.
Step2:AddingaDataWebControlandBindingit totheObjectDataSource
OncetheObjectDataSourcehasbeenaddedtothepageandconfigured,we'rereadytoadddataWebcontrols tothepagetodisplaythedatareturnedbytheObjectDataSource'sSelect method.AnydataWebcontrolcan beboundtoanObjectDataSourcelet'slookatdisplayingtheObjectDataSource'sdatainaGridView, DetailsView,andFormView.
4of14
BindingaGridViewtotheObjectDataSource
AddaGridViewcontrolfromtheToolboxto SimpleDisplay.aspx'sdesignsurface.FromtheGridView's smarttag,choosetheObjectDataSourcecontrolweaddedinStep1.Thiswillautomaticallycreatea BoundFieldintheGridViewforeachpropertyreturnedbythedatafromtheObjectDataSource'sSelect method(namely,thepropertiesdefinedbytheProductsDataTable).
Figure6:AGridViewHasBeenAddedtothePageandBoundtotheObjectDataSource Youcanthencustomize,rearrange,orremovetheGridView'sBoundFieldsbyclickingtheEditColumns optionfromthesmarttag.
5of14
Figure7:ManagetheGridView'sBoundFieldsThroughtheEditColumnsDialogBox TakeamomenttomodifytheGridView'sBoundFields,removingtheProductID,SupplierID,CategoryID, QuantityPerUnit,UnitsInStock,UnitsOnOrder,andReorderLevel BoundFields.Simplyselectthe BoundFieldfromthelistinthebottomleftandclickthedeletebutton(theredX)toremovethem.Next, RearrangetheBoundFieldssothattheCategoryName andSupplierName BoundFieldsprecedethe UnitPrice BoundFieldbyselectingtheseBoundFieldsandclickingtheuparrow.SettheHeaderText propertiesoftheremainingBoundFieldsto Products,Category,Supplier,andPrice,respectively.Next, havethePrice BoundFieldformattedasacurrencybysettingtheBoundField'sHtmlEncode propertytoFalse anditsDataFormatString propertyto{0:c}.Finally,horizontallyalignthePrice totherightandthe Discontinued checkboxinthecenterviatheItemStyle/HorizontalAlign property.
<asp:GridViewID="GridView1"runat="server" AutoGenerateColumns="False"DataKeyNames="ProductID" DataSourceID="ObjectDataSource1"EnableViewState="False"> <Columns> <asp:BoundFieldDataField="ProductName" HeaderText="Product"SortExpression="ProductName"/> <asp:BoundFieldDataField="CategoryName" HeaderText="Category"ReadOnly="True" SortExpression="CategoryName"/> <asp:BoundFieldDataField="SupplierName" HeaderText="Supplier"ReadOnly="True" SortExpression="SupplierName"/> <asp:BoundFieldDataField="UnitPrice" DataFormatString="{0:c}"HeaderText="Price" HtmlEncode="False"SortExpression="UnitPrice"> <ItemStyleHorizontalAlign="Right"/> </asp:BoundField> <asp:CheckBoxFieldDataField="Discontinued" HeaderText="Discontinued"SortExpression="Discontinued"> <ItemStyleHorizontalAlign="Center"/> </asp:CheckBoxField> </Columns> </asp:GridView>
6of14
Figure8:TheGridView'sBoundFieldsHaveBeenCustomized
UsingThemesforaConsistentLook
Thesetutorialsstrivetoremoveanycontrollevelstylesettings,insteadusingcascadingstylesheetsdefinedin anexternalfilewheneverpossible.TheStyles.css filecontainsDataWebControlStyle,HeaderStyle, RowStyle,andAlternatingRowStyle CSSclassesthatshouldbeusedtodictatetheappearanceofthedata Webcontrolsusedinthesetutorials.Toaccomplishthis,wecouldsettheGridView'sCssClass propertyto DataWebControlStyle,anditsHeaderStyle,RowStyle,andAlternatingRowStyle properties'CssClass propertiesaccordingly. IfwesettheseCssClass propertiesattheWebcontrolwe'dneedtoremembertoexplicitlysettheseproperty valuesforeachandeverydataWebcontroladdedtoourtutorials.Amoremanageableapproachistodefine thedefaultCSSrelatedpropertiesfortheGridView,DetailsView,andFormViewcontrolsusingaTheme.A Themeisacollectionofcontrollevelpropertysettings,images,andCSSclassesthatcanbeappliedtopages acrossasitetoenforceacommonlookandfeel. OurThemewon'tincludeanyimagesorCSSfiles(we'llleavethestylesheet Styles.css asis,definedinthe rootfolderofthewebapplication),butwillincludetwoSkins.ASkinisafilethatdefinesthedefault propertiesforaWebcontrol.Specifically,we'llhaveaSkinfilefortheGridViewandDetailsViewcontrols, indicatingthedefault CssClassrelatedproperties. StartbyaddinganewSkinFiletoyourprojectnamedGridView.skin byrightclickingontheprojectname intheSolutionExplorerandchoosingAddNewItem.
Figure9:AddaSkinFileNamedGridView.skin SkinfilesneedtobeplacedinaTheme,whicharelocatedintheApp_Themes folder.Sincewedon'tyethave suchafolder,VisualStudiowillkindlyoffertocreateoneforuswhenaddingourfirstSkin.ClickYesto createtheApp_Theme folderandplacethenewGridView.skin filethere.
7of14
Figure10:LetVisualStudioCreatetheApp_Theme Folder ThiswillcreateanewThemeintheApp_Themes foldernamedGridViewwiththeSkinfileGridView.skin.
Figure11:TheGridViewThemehasBeenAddedtotheApp_Theme Folder RenametheGridViewThemetoDataWebControls(rightclickontheGridViewfolderintheApp_Theme folderandchooseRename).Next,enterthefollowingmarkupintotheGridView.skin file:
<asp:GridViewrunat="server"CssClass="DataWebControlStyle"> <AlternatingRowStyleCssClass="AlternatingRowStyle"/> <RowStyleCssClass="RowStyle"/> <HeaderStyleCssClass="HeaderStyle"/> </asp:GridView>
ThisdefinesthedefaultpropertiesfortheCssClassrelatedpropertiesforanyGridViewinanypagethatuses theDataWebControlsTheme.Let'saddanotherSkinfortheDetailsView,adataWebcontrolthatwe'llbe usingshortly.AddanewSkintotheDataWebControlsThemenamedDetailsView.skin andaddthe followingmarkup:
<asp:DetailsViewrunat="server"CssClass="DataWebControlStyle"> <AlternatingRowStyleCssClass="AlternatingRowStyle"/> <RowStyleCssClass="RowStyle"/> <FieldHeaderStyleCssClass="HeaderStyle"/> </asp:DetailsView>
WithourThemedefined,thelaststepistoapplytheThemetoourASP.NETpage.AThemecanbeapplied
8of14
onapagebypagebasisorforallpagesinawebsite.Let'susethisthemeforallpagesinthewebsite.To accomplishthis,addthefollowingmarkuptoWeb.config's<system.web> section:
<pagesstyleSheetTheme="DataWebControls"/>
That'sallthereistoit!ThestyleSheetTheme settingindicatesthatthepropertiesspecifiedintheTheme shouldnotoverridethepropertiesspecifiedatthecontrollevel.TospecifythatThemesettingsshouldtrump controlsettings,usethetheme attributeinplaceofstyleSheetThemeunfortunately,Themesettings specifiedviathetheme attributedonotappearintheVisualStudioDesignview.RefertoASP.NETThemes andSkinsOverviewandServerSideStylesUsingThemesformoreinformationonThemesandSkinssee HowTo:ApplyASP.NETThemesformoreonconfiguringapagetouseatheme.
Figure12:TheGridViewDisplaystheProduct'sName,Category,Supplier,Price,andDiscontinued Information
DisplayingOneRecordataTimeinthe DetailsView
TheGridViewdisplaysonerowforeachrecordreturnedbythedatasourcecontroltowhichit'sbound.There aretimes,however,whenwemaywanttodisplayasolerecordorjustonerecordatatime.TheDetailsView control offersthisfunctionality,renderingasanHTML<table> withtwocolumnsandonerowforeach columnorpropertyboundtothecontrol.YoucanthinkoftheDetailsViewasaGridViewwithasinglerecord rotated90degrees. StartbyaddingaDetailsViewcontrol abovetheGridViewinSimpleDisplay.aspx.Next,bindittothesame ObjectDataSourcecontrolastheGridView.LikewiththeGridView,aBoundFieldwillbeaddedtothe DetailsViewforeachpropertyintheobjectreturnedbytheObjectDataSource'sSelect method.Theonly differenceisthattheDetailsView'sBoundFieldsarelaidouthorizontallyratherthanvertically.
9of14
Figure13:AddaDetailsViewtothePageandBindittotheObjectDataSource LiketheGridView,theDetailsView'sBoundFieldscanbetweakedtoprovideamorecustomizeddisplayof thedatareturnedbytheObjectDataSource.Figure14showstheDetailsViewafteritsBoundFieldsand CssClass propertieshavebeenconfiguredtomakeitsappearancesimilartotheGridViewexample.
Figure14:TheDetailsViewShowsaSingleRecord
10of14
NotethattheDetailsViewonlydisplaysthefirstrecordreturnedbyitsdatasource.Toallowtheusertostep throughalloftherecords,oneatatime,wemustenablepagingfortheDetailsView.Todoso,returnto VisualStudioandchecktheEnablePagingcheckboxintheDetailsView'ssmarttag.
Figure15EnablePagingintheDetailsViewControl
Figure16:WithPagingEnabled,theDetailsViewAllowstheUsertoViewAnyoftheProducts We'lltalkmoreaboutpaginginfuturetutorials.
11of14
AMoreFlexibleLayoutforShowingOneRecord ataTime
TheDetailsViewisprettyrigidinhowitdisplayseachrecordreturnedfromtheObjectDataSource.Wemay wantamoreflexibleviewofthedata.Forexample,ratherthanshowingtheproduct'sname,category, supplier,price,anddiscontinuedinformationeachonaseparaterow,wemaywanttoshowtheproductname andpriceinan<h4> heading,withthecategoryandsupplierinformationappearingbelowthenameandprice inasmallerfontsize.Andwemaynotcaretoshowthepropertynames(Product,Category,andsoon)next tothevalues. TheFormViewcontrol providesthislevelofcustomization.Ratherthanusingfields(liketheGridViewand DetailsViewdo),theFormViewusestemplates,whichallowforamixofWebcontrols,staticHTML,and databindingsyntax.IfyouarefamiliarwiththeRepeatercontrolfromASP.NET1.x,youcanthinkofthe FormViewastheRepeaterforshowingasinglerecord. AddaFormViewcontroltotheSimpleDisplay.aspx page'sdesignsurface.InitiallytheFormViewdisplays asagrayblock,informingusthatweneedtoprovide,atminimum,thecontrol'sItemTemplate.
Figure17:TheFormViewMustIncludeanItemTemplate YoucanbindtheFormViewdirectlytoadatasourcecontrolthroughtheFormView'ssmarttag,whichwill createadefault ItemTemplate automatically(alongwithanEditItemTemplate andInsertItemTemplate, iftheObjectDatatSourcecontrol'sInsertMethod andUpdateMethod propertiesareset).However,forthis examplelet'sbindthedatatotheFormViewandspecifyitsItemTemplate manually.Startbysettingthe FormView'sDataSourceID propertytotheID oftheObjectDataSourcecontrol,ObjectDataSource1.Next, createtheItemTemplate sothatitdisplaystheproduct'snameandpriceinan<h4> elementandthecategory andshippernamesbeneaththatinasmallerfontsize.
<asp:FormViewID="FormView1"runat="server" DataSourceID="ObjectDataSource1"EnableViewState="False"> <ItemTemplate>
12of14
<h4><%#Eval("ProductName")%> (<%#Eval("UnitPrice","{0:c}")%>)</h4> Category:<%#Eval("CategoryName")%> Supplier:<%#Eval("SupplierName")%> </ItemTemplate> </asp:FormView>
Figure18:TheFirstProduct(Chai)isDisplayedinaCustomFormat The<%#Eval(propertyName)%> isthedatabindingsyntax.TheEval methodreturnsthevalueofthe specifiedpropertyforthecurrentobjectbeingboundtotheFormViewcontrol.CheckoutAlexHomer's articleSimplifiedandExtendedDataBindingSyntaxinASP.NET2.0formoreinformationontheinsand outsofdatabinding. LiketheDetailsView,theFormViewonlyshowsthefirstrecordreturnedfromtheObjectDataSource.You canenablepagingintheFormViewtoallowvisitorstostepthroughtheproductsoneatatime.
Summary
AccessinganddisplayingdatafromaBusinessLogicLayercanbeaccomplishedwithoutwritingalineofcode thankstoASP.NET2.0'sObjectDataSourcecontrol.TheObjectDataSourceinvokesaspecifiedmethodofa classandreturnstheresults.TheseresultscanbedisplayedinadataWebcontrolthat'sboundtothe ObjectDataSource.InthistutorialwelookedatbindingtheGridView,DetailsView,andFormViewcontrols totheObjectDataSource. Sofarwe'veonlyseenhowtousetheObjectDataSourcetoinvokeaparameterlessmethod,butwhatifwe wanttoinvokeamethodthatexpectsinputparameters,suchastheProductBLL class's GetProductsByCategoryID(categoryID)?Inordertocallamethodthatexpectsoneormoreparameters wemustconfiguretheObjectDataSourcetospecifythevaluesfortheseparameters.We'llseehowto accomplishthisinournexttutorial. HappyProgramming!
FurtherReading
13of14
Formoreinformationonthetopicsdiscussedinthistutorial,refertothefollowingresources: CreateYourOwnDataSourceControls GridViewExamplesforASP.NET2.0 SimplifiedandExtendedDataBindingSyntaxinASP.NET2.0 ThemesinASP.NET2.0 ServerSideStylesUsingThemes HowTo:ApplyASP.NETThemesProgrammatically
AbouttheAuthor
ScottMitchell,authorofsixASP/ASP.NETbooksandfounderof4GuysFromRolla.com,hasbeenworking withMicrosoftWebtechnologiessince1998.Scottworksasanindependentconsultant,trainer,andwriter, recentlycompletinghislatestbook,SamsTeachYourselfASP.NET2.0in24Hours.Hecanbereachedat [email protected] orviahisblog,whichcanbefoundathttp://ScottOnWriting.NET.
SpecialThanksTo
Thistutorialserieswasreviewedbymanyhelpfulreviewers.LeadreviewerforthistutorialwasHilton Giesenow.InterestedinreviewingmyupcomingMSDNarticles?Ifso,dropmealineat [email protected].
14of14