Data Tutorial 04 Cs
Data Tutorial 04 Cs
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
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.
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>
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).
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.
7of14
WithourThemedefined,thelaststepistoapplytheThemetoourASP.NETpage.AThemecanbeapplied
8of14
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
Figure14:TheDetailsViewShowsaSingleRecord
10of14
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
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
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