Sunteți pe pagina 1din 19

Thistutorialispartofaset.FindoutmoreaboutdataaccesswithASP.

NETintheWorkingwithData
inASP.NET2.0sectionoftheASP.NETsiteathttp://www.asp.net/learn/dataaccess/default.aspx.

WorkingwithDatainASP.NET2.0::Displaying
DatawiththeDataListandRepeaterControls
Introduction
Inalloftheexamplesthroughoutthepast28tutorials,ifweneededtodisplaymultiplerecordsfromadatasource
weturnedtotheGridViewcontrol.TheGridViewrendersarowforeachrecordinthedatasource,displayingthe
recordsdatafieldsincolumns.WhiletheGridViewmakesitasnaptodisplay,pagethrough,sort,edit,anddelete
data,itsappearanceisabitboxy.Moreover,themarkupresponsiblefortheGridViewsstructureisfixed it
includesanHTML<table> withatablerow(<tr>)foreachrecordandatablecell(<td>)foreachfield.
Toprovideagreaterdegreeofcustomizationintheappearanceandrenderedmarkupwhendisplayingmultiple
records,ASP.NET2.0offerstheDataListandRepeatercontrols(bothofwhichwerealsoavailableinASP.NET
version1.x).TheDataListandRepeatercontrolsrendertheircontentusingtemplatesratherthanBoundFields,
CheckBoxFields,ButtonFields,andsoon.LiketheGridView,theDataListrendersasanHTML<table>,but
allowsformultipledatasourcerecordstobedisplayedpertablerow.TheRepeater,ontheotherhand,rendersno
additionalmarkupthanwhatyouexplicitlyspecify,andisanidealcandidatewhenyouneedprecisecontrolover
themarkupemitted.
Overthenextdozenorsotutorials,welllookatbuildingcommonreportingpatternswiththeDataListand
Repeatercontrols,startingwiththebasicsofdisplayingdatawiththesecontrols templates.Wellseehowto
formatthesecontrols,howtoalterthelayoutofdatasourcerecordsintheDataList,commonmaster/details
scenarios,waystoeditanddeletedata,howtopagethroughrecords,andsoon.

Step1:AddingtheDataListandRepeaterTutorial
WebPages
Beforewestartthistutorial,letsfirsttakeamomenttoaddtheASP.NETpageswellneedforthistutorialandthe
nextfewtutorialsdealingwithdisplayingdatausingtheDataListandRepeater.Startbycreatinganewfolderin
theprojectnamedDataListRepeaterBasics.Next,addthefollowingfiveASP.NETpagestothisfolder,having
allofthemconfiguredtousethemasterpageSite.master:
Default.aspx
l Basics.aspx
l Formatting.aspx
l RepeatColumnAndDirection.aspx
l NestedControls.aspx
l

1 of19

Figure1:CreateaDataListRepeaterBasics FolderandAddtheTutorialASP.NETPages
OpentheDefault.aspx pageanddragtheSectionLevelTutorialListing.ascx UserControlfromthe
UserControls folderontotheDesignsurface.ThisUserControl,whichwecreatedintheMasterPagesandSite
Navigation tutorial,enumeratesthesitemapanddisplaysthetutorialsfromthecurrentsectioninabulletedlist.

2 of19

Figure2:AddtheSectionLevelTutorialListing.ascx UserControltoDefault.aspx
InordertohavethebulletedlistdisplaytheDataListandRepeatertutorialswellbecreating,weneedtoaddthem
tothesitemap.OpentheWeb.sitemap fileandaddthefollowingmarkupaftertheAddingCustomButtons site
mapnodemarkup:
<siteMapNode
title="DisplayingDatawiththeDataListandRepeater"
description="SamplesofReportsthatUsetheDataListandRepeaterControls"
url="~/DataListRepeaterBasics/Default.aspx">

<siteMapNode
title="BasicExamples"
description="Examinesthebasicsfordisplayingdatausingthe
DataListandRepeatercontrols."
url="~/DataListRepeaterBasics/Basics.aspx"/>
<siteMapNode
title="Formatting"
description="LearnhowtoformattheDataListandtheWebcontrolswithin
theDataListandRepeater'stemplates."
url="~/DataListRepeaterBasics/Formatting.aspx"/>
<siteMapNode
title="AdjustingtheDataList&apossLayout"
description="IllustrateshowtoaltertheDataList'slayout,showing
multipledatasourcerecordspertablerow."
url="~/DataListRepeaterBasics/RepeatColumnAndDirection.aspx"/>
<siteMapNode
title="NestingaRepeaterwithinaDataList"
description="LearnhowtonestaRepeaterwithinthetemplateofaDataList."
url="~/DataListRepeaterBasics/NestedControls.aspx"/>

</siteMapNode>

3 of19

Figure3:UpdatetheSiteMaptoIncludetheNewASP.NETPages

Step2:DisplayingProductInformationwiththe
DataList
SimilartotheFormView,theDataListcontrolsrenderedoutputdependsupontemplatesratherthanBoundFields,
CheckBoxFields,andsoon.UnliketheFormView,theDataListisdesignedtodisplayasetofrecordsratherthana
solitaryone.LetsbeginthistutorialwithalookatbindingproductinformationtoaDataList.Startbyopeningthe
Basics.aspx pageintheDataListRepeaterBasics folder.Next,dragaDataListfromtheToolboxontothe
Designer.AsFigure4illustrates,beforespecifyingtheDataListstemplates,theDesignerdisplaysitasagraybox.

Figure4:DragtheDataListFromtheToolboxOntotheDesigner
FromtheDataListssmarttag,addanewObjectDataSourceandconfigureittousetheProductsBLL classs
GetProducts method.SincewerecreatingareadonlyDataListinthistutorial,setthedropdownlistto(None)in
thewizardsINSERT,UPDATE,andDELETEtabs.

4 of19

Figure5:OpttoCreateaNewObjectDataSource

Figure6:ConfiguretheObjectDataSourcetoUsetheProductsBLL Class

5 of19

Figure7:RetrieveInformationAboutAlloftheProductsUsingtheGetProducts Method
AfterconfiguringtheObjectDataSourceandassociatingitwiththeDataListthroughitssmarttag,VisualStudio
willautomaticallycreateanItemTemplate intheDataListthatdisplaysthenameandvalueofeachdatafield
returnedbythedatasource(seethemarkupbelow).ThisdefaultItemTemplatesappearanceisidenticaltothatof
thetemplatesautomaticallycreatedwhenbindingadatasourcetotheFormViewthroughtheDesigner.
<asp:DataListID="DataList1"runat="server"DataKeyField="ProductID"
DataSourceID="ObjectDataSource1"EnableViewState="False">
<ItemTemplate>
ProductID:<asp:LabelID="ProductIDLabel"runat="server"
Text='<%#Eval("ProductID")%>'/><br/>
ProductName:<asp:LabelID="ProductNameLabel"runat="server"
Text='<%#Eval("ProductName")%>'/><br/>
SupplierID:<asp:LabelID="SupplierIDLabel"runat="server"
Text='<%#Eval("SupplierID")%>'/><br/>
CategoryID:<asp:LabelID="CategoryIDLabel"runat="server"
Text='<%#Eval("CategoryID")%>'/><br/>
QuantityPerUnit:<asp:LabelID="QuantityPerUnitLabel"runat="server"
Text='<%#Eval("QuantityPerUnit")%>'/><br/>
UnitPrice:<asp:LabelID="UnitPriceLabel"runat="server"
Text='<%#Eval("UnitPrice")%>'/><br/>
UnitsInStock:<asp:LabelID="UnitsInStockLabel"runat="server"
Text='<%#Eval("UnitsInStock")%>'/><br/>
UnitsOnOrder:<asp:LabelID="UnitsOnOrderLabel"runat="server"
Text='<%#Eval("UnitsOnOrder")%>'/><br/>
ReorderLevel:<asp:LabelID="ReorderLevelLabel"runat="server"
Text='<%#Eval("ReorderLevel")%>'/><br/>
Discontinued:<asp:LabelID="DiscontinuedLabel"runat="server"
Text='<%#Eval("Discontinued")%>'/><br/>
CategoryName:<asp:LabelID="CategoryNameLabel"runat="server"
Text='<%#Eval("CategoryName")%>'/><br/>
SupplierName:<asp:LabelID="SupplierNameLabel"runat="server"
Text='<%#Eval("SupplierName")%>'/><br/>

6 of19

<br/>
</ItemTemplate>
</asp:DataList>
<asp:ObjectDataSourceID="ObjectDataSource1"runat="server"
OldValuesParameterFormatString="original_{0}"
SelectMethod="GetProducts"TypeName="ProductsBLL">
</asp:ObjectDataSource>

Note: RecallthatwhenbindingadatasourcetoaFormViewcontrolthroughtheFormViewssmarttag,Visual
StudiocreatedanItemTemplate,InsertItemTemplate,andEditItemTemplate.WiththeDataList,however,
onlyanItemTemplate iscreated.ThisisbecausetheDataListdoesnothavethesamebuiltineditingandinserting
supportofferedbytheFormView.TheDataListdoescontainedit anddeleterelatedevents,andeditingand
deletingsupportcanbeaddedwithabitofcode,buttheresnosimpleoutoftheboxsupportaswiththe
FormView.WellseehowtoincludeeditinganddeletingsupportwiththeDataListinafuturetutorial.
Letstakeamomenttoimprovetheappearanceofthistemplate.Ratherthandisplayingallofthedatafields,lets
onlydisplaytheproductsname,supplier,category,quantityperunit,andunitprice.Moreover,letsdisplaythe
nameinan<h4> headingandlayouttheremainingfieldsusinga<table> beneaththeheading.
TomakethesechangesyoucaneitherusethetemplateeditingfeaturesintheDesigner fromtheDataLists
smarttagclickontheEditTemplateslink oryoucanmodifythetemplatemanuallythroughthepages
declarativesyntax.IfyouusetheEditTemplatesoptionintheDesigner,yourresultingmarkupmaynotmatchthe
followingmarkupexactly,butwhenviewedthroughabrowsershouldlookverysimilartothescreenshotshownin
Figure8.
<asp:DataListID="DataList1"runat="server"DataKeyField="ProductID"
DataSourceID="ObjectDataSource1"EnableViewState="False">
<ItemTemplate>
<h4><asp:LabelID="ProductNameLabel"runat="server"
Text='<%#Eval("ProductName")%>'/></h4>
<tableborder="0">
<tr>
<tdclass="ProductPropertyLabel">Category:</td>
<td><asp:LabelID="CategoryNameLabel"runat="server"
Text='<%#Eval("CategoryName")%>'/></td>
<tdclass="ProductPropertyLabel">Supplier:</td>
<td><asp:LabelID="SupplierNameLabel"runat="server"
Text='<%#Eval("SupplierName")%>'/></td>
</tr>
<tr>
<tdclass="ProductPropertyLabel">Qty/Unit:</td>
<td><asp:LabelID="QuantityPerUnitLabel"runat="server"
Text='<%#Eval("QuantityPerUnit")%>'/></td>
<tdclass="ProductPropertyLabel">Price:</td>
<td><asp:LabelID="UnitPriceLabel"runat="server"
Text='<%#Eval("UnitPrice","{0:C}")%>'/></td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>

Note: TheexampleaboveusesLabelWebcontrolswhoseText propertyisassignedthevalueofthedatabinding


syntax.Alternatively,wecouldhaveomittedtheLabelsaltogether,typinginjustthedatabindingsyntax.Thatis,
insteadofusing<asp:LabelID="CategoryNameLabel"runat="server"Text='<%#Eval("CategoryName")
%>'/> wecouldhaveinsteadusedthedeclarativesyntax<%#Eval("CategoryName")%> .
LeavingintheLabelWebcontrols,however,offertwoadvantages.First,itprovidesaneasiermeansforformatting
thedatabasedonthedata,aswellseeinthenexttutorial.Second,theEditTemplatesoptionintheDesigner
doesntdisplaydeclarativedatabindingsyntaxthatappearsoutsideofsomeWebcontrol.Instead,theEdit

7 of19

TemplatesinterfaceisdesignedtofacilitateworkingwithstaticmarkupandWebcontrolsandassumesthatany
databindingwillbedonethroughtheEditDataBindingsdialogbox,whichisaccessiblefromtheWebcontrols
smarttags.
Therefore,whenworkingwiththeDataList,whichprovidestheoptionofeditingthetemplatesthroughthe
Designer,IprefertouseLabelWebcontrolssothatthecontentisaccessiblethroughtheEditTemplatesinterface.
Aswellseeshortly,theRepeaterrequiresthatthetemplatescontentsbeeditedfromtheSourceview.
Consequently,whencraftingtheRepeaterstemplatesIlloftenomittheLabelWebcontrolsunlessIknowIll
needtoformattheappearanceofthedataboundtextbasedonprogrammaticlogic.

Figure8:EachProductsOutputisRenderedUsingtheDataListsItemTemplate

Step3:ImprovingtheAppearanceoftheDataList
LiketheGridView,theDataListoffersanumberofstylerelatedproperties,suchas Font,ForeColor,BackColor,
CssClass,ItemStyle,AlternatingItemStyle,SelectedItemStyle,andsoon.Whenworkingwiththe
GridViewandDetailsViewcontrols,wecreatedSkinfilesintheDataWebControls Themethatpredefinedthe
CssClass propertiesforthesetwocontrolsandtheCssClass propertyforseveraloftheirsubproperties
(RowStyle,HeaderStyle,andsoon).LetsdothesamefortheDataList.
AsdiscussedintheDisplayingDataWiththeObjectDataSourcetutorial,aSkinfilespecifiesthedefault
appearancerelatedpropertiesforaWebcontrolaThemeisacollectionofSkin,CSS,image,andJavaScriptfiles
thatdefineaparticularlookandfeelforawebsite.IntheDisplayingDataWiththeObjectDataSource tutorial,we
createdaDataWebControls Theme(whichisimplementedasafolderwithintheApp_Themes folder)thathas,
currently,twoSkinfilesGridView.skin andDetailsView.skin.LetsaddathirdSkinfiletospecifythepre

8 of19

definedstylesettingsfortheDataList.
ToaddaSkinfile,rightclickontheApp_Themes/DataWebControls folder,chooseAddaNewItem,andselect
theSkinFileoptionfromthelist.NamethefileDataList.skin.

Figure9:CreateaNewSkinFileNamedDataList.skin
UsethefollowingmarkupfortheDataList.skin file:
<asp:DataListrunat="server"CssClass="DataWebControlStyle">
<AlternatingItemStyleCssClass="AlternatingRowStyle"/>
<ItemStyleCssClass="RowStyle"/>
<HeaderStyleCssClass="HeaderStyle"/>
<FooterStyleCssClass="FooterStyle"/>
<SelectedItemStyleCssClass="SelectedRowStyle"/>
</asp:DataList>

ThesesettingsassignthesameCSSclassestotheappropriateDataListpropertiesaswereusedwiththeGridView
andDetailsViewcontrols.TheCSSclassesusedhereDataWebControlStyle,AlternatingRowStyle,
RowStyle,andsoon aredefinedinthe Styles.css fileandwereaddedinprevioustutorials.
WiththeadditionofthisSkinfile,theDataListsappearanceisupdatedintheDesigner(youmayneedtorefresh
theDesignerviewtoseetheeffectsofthenewSkinfilefromtheViewmenu,chooseRefresh).AsFigure10
shows,eachalternatingproducthasalightpinkbackgroundcolor.

9 of19

Figure10:CreateaNewSkinFileNamedDataList.skin

Step4:ExploringtheDataListsOtherTemplates
InadditiontotheItemTemplate,theDataListsupportssixotheroptionaltemplates:
HeaderTemplate ifprovided,addsaheaderrowtotheoutputandisusedtorenderthisrow
l AlternatingItemTemplate usedtorenderalternatingitems
l SelectedItemTemplate usedtorendertheselecteditemtheselecteditemistheitemwhoseindex
correspondstotheDataListsSelectedIndex property
l EditItemTemplate usedtorendertheitembeingedited
l SeparatorTemplate ifprovided,addsaseparatorbetweeneachitemandisusedtorenderthisseparator
l FooterTemplate ifprovided,addsafooterrowtotheoutputandisusedtorenderthisrow
l

10 of19

WhenspecifyingtheHeaderTemplate orFooterTemplate,theDataListaddsanadditionalheaderorfooterrowto
therenderedoutput.LikewiththeGridViewsheaderandfooterrows,theheaderandfooterinaDataListarenot
boundtodata.Therefore,anydatabindingsyntaxintheHeaderTemplate orFooterTemplate thatattemptsto
accessbounddatawillreturnablankstring.
Note: AswesawintheDisplayingSummaryInformationintheGridViewsFooter tutorial,whiletheheaderand
footerrowsdontsupportdatabindingsyntax,dataspecificinformationcanbeinjecteddirectlyintotheserows
fromtheGridViewsRowDataBound eventhandler.Thistechniquecanbeusedtobothcalculaterunningtotalsor
otherinformationfromthedataboundtothecontrolaswellasassignthatinformationtothefooter.Thissame
conceptcanbeappliedtotheDataListandRepeatercontrolstheonlydifferenceisthatfortheDataListand
RepeatercreateaneventhandlerfortheItemDataBound event(insteadoffortheRowDataBound event).
Forourexample,letshavethetitleProductInformation displayedatthetopoftheDataListsresultsinan<h3>
heading.Toaccomplishthis,addaHeaderTemplate withtheappropriatemarkup.FromtheDesigner,thiscanbe
accomplishedbyclickingontheEditTemplateslinkintheDataListssmarttag,choosingtheHeaderTemplate
fromthedropdownlist,andtypinginthetextafterpickingtheHeading3optionfromthestyledropdownlist(see
Figure11).

Figure11:AddaHeaderTemplate withtheText ProductInformation


Alternatively,thiscanbeaddeddeclarativelybyenteringthefollowingmarkupwithinthe<asp:DataList> tags:
<HeaderTemplate>
<h3>ProductInformation</h3>
</HeaderTemplate>

Toaddabitofspacebetweeneachproductlisting,letsaddaSeparatorTemplate thatincludesalinebetween
eachsection.Thehorizontalruletag(<hr>),addssuchadivider.CreatetheSeparatorTemplate sothatithasthe
followingmarkup:
<SeparatorTemplate>
<hr/>
</SeparatorTemplate>

11 of19

Note: LiketheHeaderTemplate andFooterTemplates,theSeparatorTemplate isnotboundtoanyrecordfrom


thedatasourceandthereforecannotdirectlyaccessthedatasourcerecordsboundtotheDataList.
Aftermakingthisaddition,whenviewingthepagethroughabrowseritshouldlooksimilartoFigure12.Notethe
headerrowandthelinebetweeneachproductlisting.

Figure12:TheDataListIncludesaHeaderRowandaHorizontalRuleBetweenEachProductListing

Step5:RenderingSpecificMarkupwiththeRepeater
Control
IfyoudoaView/SourcefromyourbrowserwhenvisitingtheDataListexamplefromFigure12,youllseethatthe
DataListemitsanHTML<table> thatcontainsatablerow(<tr>)withasingletablecell(<td>)foreachitem
boundtotheDataList.Thisoutput,infact,isidenticaltowhatwouldbeemittedfromaGridViewwithasingle
TemplateField.Aswellseeinafuturetutorial,theDataListdoesallowfurthercustomizationoftheoutput,
enablingustodisplaymultipledatasourcerecordspertablerow.
WhatifyoudontwanttoemitanHTML<table>,though?Fortotalandcompletecontroloverthemarkup
generatedbyadataWebcontrol,wemustusetheRepeatercontrol.LiketheDataList,theRepeaterisconstructed
basedupontemplates.TheRepeater,however,onlyoffersthefollowingfivetemplates:
HeaderTemplate ifprovided,addsthespecifiedmarkupbeforetheitems
l ItemTemplate usedtorenderitems
l

12 of19

AlternatingItemTemplate ifprovided,usedtorenderalternatingitems
l SeparatorTemplate ifprovided,addsthespecifiedmarkupbetweeneachitem
l FooterTemplate ifprovided,addsthespecifiedmarkupaftertheitems
l

InASP.NET1.x,theRepeatercontrolwascommonlyusedtodisplayabulletedlistwhosedatacamefromsome
datasource.Insuchacase,theHeaderTemplate andFooterTemplates wouldcontaintheopeningandclosing
<ul> tags,respectively,whiletheItemTemplate wouldcontain<li> elementswithdatabindingsyntax.This
approachcanstillbeusedinASP.NET2.0aswesawintwoexamplesintheMasterPagesandSiteNavigation
tutorial:
l

IntheSite.master masterpage,aRepeaterwasusedtodisplayabulletedlistofthetoplevelsitemap
contents(BasicReporting,FilteringReports,CustomizedFormatting,andsoon)another,nestedRepeater
wasusedtodisplaythechildrensectionsofthetoplevelsections
InSectionLevelTutorialListing.ascx,aRepeaterwasusedtodisplayabulletedlistofthechildren
sectionsofthecurrentsitemapsection

Note: ASP.NET2.0introducesthenewBulletedListcontrol,whichcanbeboundtoadatasourcecontrolinorder
todisplayasimplebulletedlist.WiththeBulletedListcontrolwedonotneedtospecifyanyofthelistrelated
HTMLinstead,wesimplyindicatethedatafieldtodisplayasthetextforeachlistitem.
TheRepeaterservesasa catchall dataWebcontrol.Ifthereisnotanexistingcontrolthatgeneratestheneeded
markup,theRepeatercontrolcanbeused.ToillustrateusingtheRepeater,letshavethelistofcategories
displayedabovetheProductInformationDataListcreatedinStep2.Inparticular,letshavethecategories
displayedinasinglerowHTML<table> witheachcategorydisplayedasacolumninthetable.
Toaccomplishthis,startbydraggingaRepeatercontrolfromtheToolboxontotheDesigner,abovetheProduct
InformationDataList.AswiththeDataList,theRepeaterinitiallydisplaysasagrayboxuntilitstemplateshave
beendefined.

13 of19

Figure13:AddaRepeatertotheDesigner
TheresonlyoneoptionintheRepeaterssmarttag:ChooseDataSource.OpttocreateanewObjectDataSource
andconfigureittousetheCategoriesBLL classsGetCategories method.

14 of19

Figure14:CreateaNewObjectDataSource

Figure15:ConfiguretheObjectDataSourcetoUsetheCategoriesBLL Class

15 of19

Figure16:RetrieveInformationAboutAlloftheCategoriesUsingtheGetCategories Method
UnliketheDataList,VisualStudiodoesnotautomaticallycreateanItemTemplatefortheRepeaterafterbindingit
toadatasource.Furthermore,theRepeaterstemplatescannotbeconfiguredthroughtheDesignerandmustbe
specifieddeclaratively.
Todisplaythecategoriesasasinglerow<table> withacolumnforeachcategory,weneedtheRepeatertoemit
markupsimilartothefollowing:
<table>
<tr>
<td>Category1</td>
<td>Category2</td>
...
<td>CategoryN</td>
</tr>
</table>

Sincethe<td>CategoryX</td> textistheportionthatrepeats,thiswillappearintheRepeatersItemTemplate.
Themarkupthatappearsbeforeit <table><tr> willbeplacedintheHeaderTemplate whiletheendingmarkup
</tr></table> willplacedintheFooterTemplate.Toenterthesetemplatesettings,gotothedeclarative
portionoftheASP.NETpagebyclickingontheSourcebuttoninthelowerleftcornerandtypeinthefollowing
syntax:
<asp:RepeaterID="Repeater1"runat="server"DataSourceID="ObjectDataSource2"
EnableViewState="False">
<HeaderTemplate>
<table>
<tr>
</HeaderTemplate>
<ItemTemplate>
<td><%#Eval("CategoryName")%></td>

16 of19

</ItemTemplate>
<FooterTemplate>
</tr>
</table>
</FooterTemplate>
</asp:Repeater>

TheRepeateremitstheprecisemarkupasspecifiedbyitstemplates,nothingmore,nothingless.Figure17shows
theRepeatersoutputwhenviewedthroughabrowser.

Figure17:ASingleRowHTML<table> ListsEachCategoryinaSeparateColumn

Step6:ImprovingtheAppearanceoftheRepeater
SincetheRepeateremitspreciselythemarkupspecifiedbyitstemplates,itshouldcomeasnosurprisethatthere
arenostylerelatedpropertiesfortheRepeater.ToaltertheappearanceofthecontentgeneratedbytheRepeater,
wemustmanuallyaddtheneededHTMLorCSScontentdirectlytotheRepeaterstemplates.
Forourexample,letshavethecategorycolumnsalternatebackgroundcolors,likewiththealternatingrowsinthe
DataList.Toaccomplishthis,weneedtoassigntheRowStyle CSSclasstoeachRepeateritemandthe
AlternatingRowStyle CSSclasstoeachalternatingRepeateritemthroughtheItemTemplate and
AlternatingItemTemplate templates,likeso:
<ItemTemplate>
<tdclass="RowStyle"><%#Eval("CategoryName")%></td>
</ItemTemplate>
<AlternatingItemTemplate>
<tdclass="AlternatingRowStyle"><%#Eval("CategoryName")%></td>
</AlternatingItemTemplate>

LetsalsoaddaheaderrowtotheoutputwiththetextProductCategories. Sincewedontknowhowmany
columnsourresulting<table> willbecomprisedof,thesimplestwaytogenerateaheaderrowthatisguaranteed
tospanallcolumnsistousetwo<table>s.Thefirst<table> willcontaintworows theheaderrowandarow
thatwillcontainthesecond,singlerow<table> thathasacolumnforeachcategoryinthesystem.Thatis,we
wanttoemitthefollowingmarkup:
<table>
<tr>
<th>ProductCategories</th>

17 of19

</tr>
<tr>
<td>
<table>
<tr>
<td>Category1</td>
<td>Category2</td>
...
<td>CategoryN</td>
</tr>
</table>
</td>
</tr>
</table>

ThefollowingHeaderTemplate andFooterTemplate resultinthedesiredmarkup:


<asp:RepeaterID="Repeater1"runat="server"DataSourceID="ObjectDataSource2"
EnableViewState="False">
<HeaderTemplate>
<tablecellpadding="0"cellspacing="0"style="border:solid1pxblack">
<tr>
<thclass="HeaderStyle">ProductCategories</th>
</tr>
<tr>
<td>
<tablecellpadding="4"cellspacing="0">
<tr>
</HeaderTemplate>
<ItemTemplate>
<tdclass="RowStyle"><%#Eval("CategoryName")%></td>
</ItemTemplate>
<AlternatingItemTemplate>
<tdclass="AlternatingRowStyle">
<%#Eval("CategoryName")%></td>
</AlternatingItemTemplate>
<FooterTemplate>
</tr>
</table>
</td>
</tr>
</table>
</FooterTemplate>
</asp:Repeater>

Figure18showstheRepeaterafterthesechangeshavebeenmade.

18 of19

Figure18:TheCategoryColumnsAlternateinBackgroundColorandIncludesaHeaderRow

Summary
WhiletheGridViewcontrolmakesiteasytodisplay,edit,delete,sort,andpagethroughdata,theappearanceis
veryboxyandgridlike.Formorecontrolovertheappearance,weneedtoturntoeithertheDataListorRepeater
controls.BothofthesecontrolsdisplayasetofrecordsusingtemplatesinsteadofBoundFields,CheckBoxFields,
andsoon.
TheDataListrendersasanHTML<table> that,bydefault,displayseachdatasourcerecordinasingletablerow,
justlikeaGridViewwithasingleTemplateField.Aswewillseeinafuturetutorial,however,theDataListdoes
permitmultiplerecordstobedisplayedpertablerow.TheRepeater,ontheotherhand,strictlyemitsthemarkup
specifiedinitstemplatesitdoesnotaddanyadditionalmarkupandthereforeiscommonlyusedtodisplaydatain
HTMLelementsotherthana<table> (suchasinabulletedlist).
WhiletheDataListandRepeateroffermoreflexibilityintheirrenderedoutput,theylackmanyofthebuiltin
featuresfoundintheGridView.Aswellexamineinupcomingtutorials,someofthesefeaturescanbeplugged
backinwithouttoomucheffort,butdokeepinmindthatusingtheDataListorRepeaterinlieuoftheGridView
doeslimitthefeaturesyoucanusewithouthavingtoimplementthosefeaturesyourself.
HappyProgramming!

AbouttheAuthor
ScottMitchell,authorofsixASP/ASP.NETbooksandfounderof 4GuysFromRolla.com,hasbeenworkingwith
MicrosoftWebtechnologiessince1998.Scottworksasanindependentconsultant,trainer,andwriter,recently
completinghislatestbook, SamsTeachYourselfASP.NET2.0in24Hours.Hecanbereachedat
mitchell@4guysfromrolla.comorviahisblog,whichcanbefoundatScottOnWriting.NET.

SpecialThanksTo
Thistutorialserieswasreviewedbymanyhelpfulreviewers.LeadreviewersforthistutorialincludeYaakovEllis,
LizShulok,RandySchmidt,andStacyPark.Interestedinreviewingmyupcomingarticles?Ifso,dropmealineat
mitchell@4guysfromrolla.com.

19 of19

S-ar putea să vă placă și