Data Tutorial 12 Cs
Data Tutorial 12 Cs
Thistutorialispartofaset.FindoutmoreaboutdataaccesswithASP.NETintheWorkingwithDatain
ASP.NET2.0sectionoftheASP.NETsiteathttp://www.asp.net/learn/dataaccess/default.aspx.
WorkingwithDatainASP.NET2.0::Using
TemplateFieldsintheGridViewControl
Downloadthecodeforthissample
Clickherefortheprevioustutorial
Introduction
TheGridViewiscomposedofasetoffieldsthatindicatewhatpropertiesfromtheDataSource aretobe
includedintherenderedoutputalongwithhowthedatawillbedisplayed.Thesimplestfieldtypeisthe
BoundField,whichdisplaysadatavalueastext.OtherfieldtypesdisplaythedatausingalternateHTML
elements.TheCheckBoxField,forexample,rendersasacheckboxwhosecheckedstatedependsonthevalue
ofaspecifieddatafieldtheImageFieldrendersanimagewhoseimagesourceisbaseduponaspecifieddata
field.Hyperlinksandbuttonswhosestatedependsonanunderlyingdatafieldvaluecanberenderedusingthe
HyperLinkFieldandButtonFieldfieldtypes.
WhiletheCheckBoxField,ImageField,HyperLinkField,andButtonFieldfieldtypesallowforanalternateview
ofthedata,theystillarefairlylimitedwithrespecttoformatting.ACheckBoxFieldcanonlydisplayasingle
checkbox,whereasanImageFieldcanonlydisplayasingleimage.Whatifaparticularfieldneedstodisplay
sometext,acheckbox,andanimage,allbasedupondifferentdatafieldvalues?Orwhatifwewantedto
displaythedatausingaWebcontrolotherthantheCheckBox,Image,HyperLink,orButton?Furthermore,
theBoundFieldlimitsitsdisplaytoasingledatafield.Whatifwewantedtoshowtwoormoredatafield
valuesinasingleGridViewcolumn?
ToaccommodatethislevelofflexibilitytheGridViewofferstheTemplateField,whichrendersusinga
template.AtemplatecanincludeamixofstaticHTML,Webcontrols,anddatabindingsyntax.Furthermore,
theTemplateFieldhasavarietyoftemplatesthatcanbeusedtocustomizetherenderingfordifferent
situations.Forexample,theItemTemplate isusedbydefaulttorenderthecellforeachrow,butthe
EditItemTemplate templatecanbeusedtocustomizetheinterfacewheneditingdata.
Inthistutorialwe'llexaminehowtousetheTemplateFieldtoachieveagreaterdegreeofcustomizationwith
theGridViewcontrol.Intheprecedingtutorial wesawhowtocustomizetheformattingbasedonthe
underlyingdatausingtheDataBound andRowDataBound eventhandlers.Anotherwaytocustomizethe
formattingbasedontheunderlyingdataisbycallingformattingmethodsfromwithinatemplate.We'lllookat
thistechniqueinthistutorialaswell.
ForthistutorialwewilluseTemplateFieldstocustomizetheappearanceofalistofemployees.Specifically,
we'lllistalloftheemployees,butwilldisplaytheemployee'sfirstandlastnamesinonecolumn,theirhiredate
inaCalendarcontrol,andastatuscolumnthatindicateshowmanydaysthey'vebeenemployedatthe
company.
2of17
Figure1:ThreeTemplateFieldsareUsedtoCustomizetheDisplay
Step1:BindingtheDatatotheGridView
InreportingscenarioswhereyouneedtouseTemplateFieldstocustomizetheappearance,Ifinditeasiestto
startbycreatingaGridViewcontrolthatcontainsjustBoundFieldsfirstandthentoaddnewTemplateFields
orconverttheexistingBoundFieldstoTemplateFieldsasneeded.Therefore,let'sstartthistutorialbyaddinga
GridViewtothepagethroughtheDesignerandbindingittoanObjectDataSourcethatreturnsthelistof
employees.ThesestepswillcreateaGridViewwithBoundFieldsforeachoftheemployeefields.
OpentheGridViewTemplateField.aspx pageanddragaGridViewfromtheToolboxontotheDesigner.
FromtheGridView'ssmarttagchoosetoaddanewObjectDataSourcecontrolthatinvokesthe
EmployeesBLL class'sGetEmployees() method.
3of17
Figure2:AddaNewObjectDataSourceControlthatInvokestheGetEmployees() Method
BindingtheGridViewinthismannerwillautomaticallyaddaBoundFieldforeachoftheemployeeproperties:
EmployeeID,LastName,FirstName,Title,HireDate,ReportsTo,andCountry.Forthisreportlet'snot
botherwithdisplayingtheEmployeeID,ReportsTo,orCountry properties.ToremovetheseBoundFields
youcan:
UsetheFieldsdialogboxclickontheEditColumnslinkfromtheGridView'ssmarttagtobringup
thisdialogbox.Next,selecttheBoundFieldsfromthelowerleftlistandclicktheredXbuttonto
removetheBoundField.
EdittheGridView'sdeclarativesyntaxbyhandfromtheSourceview,deletethe<asp:BoundField>
elementfortheBoundFieldyouwishtoremove.
AfteryouhaveremovedtheEmployeeID,ReportsTo,andCountry BoundFields,yourGridView'smarkup
shouldlooklike:
<asp:GridViewID="GridView1"runat="server"
AutoGenerateColumns="False"DataKeyNames="EmployeeID"
DataSourceID="ObjectDataSource1">
<Columns>
<asp:BoundFieldDataField="LastName"HeaderText="LastName"
SortExpression="LastName"/>
<asp:BoundFieldDataField="FirstName"HeaderText="FirstName"
SortExpression="FirstName"/>
<asp:BoundFieldDataField="Title"HeaderText="Title"
SortExpression="Title"/>
<asp:BoundFieldDataField="HireDate"HeaderText="HireDate"
SortExpression="HireDate"/>
</Columns>
</asp:GridView>
Takeamomenttoviewourprogressinabrowser.Atthispointyoushouldseeatablewitharecordforeach
employeeandfourcolumns:onefortheemployee'slastname,onefortheirfirstname,onefortheirtitle,and
onefortheirhiredate.
4of17
Figure3:TheLastName,FirstName,Title,andHireDate FieldsareDisplayedforEachEmployee
Step2:DisplayingtheFirstandLastNamesina
SingleColumn
Currently,eachemployee'sfirstandlastnamesaredisplayedinaseparatecolumn.Itmightbenicetocombine
themintoasinglecolumninstead.ToaccomplishthisweneedtouseaTemplateField.Wecaneitheradda
newTemplateField,addtoittheneededmarkupanddatabindingsyntax,andthendeletetheFirstName and
LastName BoundFields,orwecanconverttheFirstName BoundFieldintoaTemplateField,editthe
TemplateFieldtoincludetheLastName value,andthenremovetheLastName BoundField.
Bothapproachesnetthesameresult,butpersonallyIlikeconvertingBoundFieldstoTemplateFieldswhen
possiblebecausetheconversionautomaticallyaddsanItemTemplate andEditItemTemplate withWeb
controlsanddatabindingsyntaxtomimictheappearanceandfunctionalityoftheBoundField.Thebenefitis
thatwe'llneedtodolessworkwiththeTemplateFieldastheconversionprocesswillhaveperformedsomeof
theworkforus.
ToconvertanexistingBoundFieldintoaTemplateField,clickontheEditColumnslinkfromtheGridView's
smarttag,bringinguptheFieldsdialogbox.SelecttheBoundFieldtoconvertfromthelistinthelowerleft
cornerandthenclickthe"ConvertthisfieldintoaTemplateField"linkinthebottomrightcorner.
5of17
Figure4:ConvertaBoundFieldIntoaTemplateFieldfromtheFieldsDialogBox
GoaheadandconverttheFirstName BoundFieldintoaTemplateField.Afterthischangethere'sno
perceptivedifferenceintheDesigner.ThisisbecauseconvertingtheBoundFieldintoaTemplateFieldcreates
aTemplateFieldthatmaintainsthelookandfeeloftheBoundField.Despitetherebeingnovisualdifferenceat
thispointintheDesigner,thisconversionprocesshasreplacedtheBoundField'sdeclarativesyntax
<asp:BoundFieldDataField="FirstName"HeaderText="FirstName"SortExpression="FirstName"
/> withthefollowingTemplateFieldsyntax:
<asp:TemplateFieldHeaderText="FirstName"SortExpression="FirstName">
<EditItemTemplate>
<asp:TextBoxID="TextBox1"runat="server"
Text='<%#Bind("FirstName")%>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:LabelID="Label1"runat="server"
Text='<%#Bind("FirstName")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
Asyoucansee,theTemplateFieldconsistsoftwotemplatesanItemTemplate thathasaLabelwhoseText
propertyissettothevalueoftheFirstName datafield,andanEditItemTemplate withaTextBoxcontrol
whoseText propertyisalsosettotheFirstName datafield.Thedatabindingsyntax<%#
Bind("fieldName")%> indicatesthatthedatafieldfieldName isboundtothespecifiedWebcontrol
property.
ToaddtheLastName datafieldvaluetothisTemplateFieldweneedtoaddanotherLabelWebcontrolinthe
ItemTemplate andbinditsText propertyto LastName.Thiscanbeaccomplishedeitherbyhandorthrough
theDesigner.Todoitbyhand,simplyaddtheappropriatedeclarativesyntaxtotheItemTemplate:
<asp:TemplateFieldHeaderText="FirstName"SortExpression="FirstName">
<EditItemTemplate>
<asp:TextBoxID="TextBox1"runat="server"
Text='<%#Bind("FirstName")%>'></asp:TextBox>
6of17
</EditItemTemplate>
<ItemTemplate>
<asp:LabelID="Label1"runat="server"
Text='<%#Bind("FirstName")%>'></asp:Label>
<asp:LabelID="Label2"runat="server"
Text='<%#Bind("LastName")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
ToadditthroughtheDesigner,clickontheEditTemplateslinkfromtheGridView'ssmarttag.Thiswill
displaytheGridView'stemplateeditinginterface.Inthisinterface'ssmarttagisalistofthetemplatesinthe
GridView.SinceweonlyhaveoneTemplateFieldatthispoint,theonlytemplateslistedinthedropdownlist
arethosetemplatesfortheFirstName TemplateFieldalongwiththeEmptyDataTemplate and
PagerTemplate.TheEmptyDataTemplate template,ifspecified,isusedtorendertheGridView'soutputif
therearenoresultsinthedataboundtotheGridViewthePagerTemplate,ifspecified,isusedtorenderthe
paginginterfaceforaGridViewthatsupportspaging.
Figure5:TheGridView'sTemplatesCanBeEditedThroughtheDesigner
ToalsodisplaytheLastName intheFirstName TemplateFielddragtheLabelcontrolfromtheToolboxinto
theFirstName TemplateField'sItemTemplate intheGridView'stemplateeditinginterface.
7of17
Figure6:AddaLabelWebControltotheFirstName TemplateField'sItemTemplate
AtthispointtheLabelWebcontroladdedtotheTemplateFieldhasitsText propertysetto"Label".Weneed
tochangethissothatthispropertyisboundtothevalueoftheLastName datafieldinstead.Toaccomplish
thisclickontheLabelcontrol'ssmarttagandchoosetheEditDataBindingsoption.
Figure7:ChoosetheEditDataBindingsOptionfromtheLabel'sSmartTag
ThiswillbringuptheDataBindingsdialogbox.Fromhereyoucanselectthepropertytoparticipatein
databindingfromthelistontheleftandchoosethefieldtobindthedatatofromthedropdownlistonthe
right.ChoosetheText propertyfromtheleftandtheLastName fieldfromtherightandclickOK.
8of17
9of17
<asp:TemplateFieldHeaderText="Name"
SortExpression="FirstName">
<EditItemTemplate>
<asp:TextBoxID="TextBox1"runat="server"
Text='<%#Bind("FirstName")%>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:LabelID="Label1"runat="server"
Text='<%#Bind("FirstName")%>'></asp:Label>
<asp:LabelID="Label2"runat="server"
Text='<%#Eval("LastName")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundFieldDataField="Title"HeaderText="Title"
SortExpression="Title"/>
<asp:BoundFieldDataField="HireDate"HeaderText="HireDate"
SortExpression="HireDate"/>
</Columns>
</asp:GridView>
Figure10:EachEmployee'sFirstandLastNamesareDisplayedinOneColumn
Step3:UsingtheCalendarControltoDisplaytheHiredDate Field
DisplayingadatafieldvalueastextinaGridViewisassimpleasusingaBoundField.Forcertainscenarios,
however,thedataisbestexpressedusingaparticularWebcontrolinsteadofjusttext.Suchcustomizationof
thedisplayofdataispossiblewithTemplateFields.Forexample,ratherthandisplaytheemployee'shiredate
astext,wecouldshowacalendar(usingtheCalendarcontrol)withtheirhiredatehighlighted.
Toaccomplishthis,startbyconvertingtheHiredDate BoundFieldintoaTemplateField.Simplygotothe
GridView'ssmarttagandclicktheEditColumnslink,bringinguptheFieldsdialogbox.SelecttheHiredDate
BoundFieldandclick"ConvertthisfieldintoaTemplateField."
10of17
Figure11:ConverttheHiredDate BoundFieldIntoaTemplateField
AswesawinStep2,thiswillreplacetheBoundFieldwithaTemplateFieldthatcontainsanItemTemplate
andEditItemTemplate withaLabelandTextBoxwhoseText propertiesareboundtotheHiredDate value
usingthedatabindingsyntax<%#Bind("HiredDate")%>.
ToreplacethetextwithaCalendarcontrol,editthetemplatebyremovingtheLabelandaddingaCalendar
control.FromtheDesigner,selectEditTemplatesfromtheGridView'ssmarttagandchoosetheHireDate
TemplateField'sItemTemplate fromthedropdownlist.Next,deletetheLabelcontrolanddragaCalendar
controlfromtheToolboxintothetemplateeditinginterface.
11of17
Figure12:AddaCalendarControltotheHireDate TemplateField'sItemTemplate
AtthispointeachrowintheGridViewwillcontainaCalendarcontrolinitsHiredDate TemplateField.
However,theemployee'sactualHiredDate valueisnotsetanywhereintheCalendarcontrol,causingeach
Calendarcontroltodefaulttoshowingthecurrentmonthanddate.Toremedythis,weneedtoassigneach
employee'sHiredDate totheCalendarcontrol'sSelectedDateandVisibleDateproperties.
FromtheCalendarcontrol'ssmarttag,chooseEditDataBindings.Next,bindbothSelectedDate and
VisibleDate propertiestotheHiredDate datafield.
12of17
Note:TheCalendarcontrol'sselecteddateneednotnecessarilybevisible.Forexample,aCalendarmayhave
August1st,1999astheselecteddate,butbeshowingthecurrentmonthandyear.Theselecteddateand
visibledatearespecifiedbytheCalendarcontrol'sSelectedDate andVisibleDate properties.Sincewe
wanttobothselecttheemployee'sHiredDate andmakesurethatit'sshownweneedtobindbothofthese
propertiestotheHireDate datafield.
Whenviewingthepageinabrowser,thecalendarnowshowsthemonthoftheemployee'shireddateand
selectsthatparticulardate.
Figure14:TheEmployee'sHiredDate isShownintheCalendarControl
Note:Contrarytoalltheexampleswe'veseenthusfar,forthistutorialwedidnotsetEnableViewState
propertytofalse forthisGridView.ThereasonforthisdecisionisbecauseclickingthedatesoftheCalendar
controlcausesapostback,settingtheCalendar'sselecteddatetothedatejustclicked.IftheGridView'sview
stateisdisabled,however,oneachpostbacktheGridView'sdataisreboundtoitsunderlyingdatasource,
whichcausestheCalendar'sselecteddatetobesetbacktotheemployee'sHireDate,overwritingthedate
chosenbytheuser.
Forthistutorialthisisamootdiscussionsincetheuserisnotabletoupdatetheemployee'sHireDate.It
wouldprobablybebesttoconfiguretheCalendarcontrolsothatitsdatesarenotselectable.Regardless,this
tutorialshowsthatinsomecircumstancesviewstatemustbeenabledinordertoprovidecertainfunctionality.
Step4:ShowingtheNumberofDaystheEmployee
HasWorkedfortheCompany
13of17
SofarwehaveseentwoapplicationsofTemplateFields:
Combiningtwoormoredatafieldvaluesintoonecolumn,and
ExpressingadatafieldvalueusingaWebcontrolinsteadoftext
AthirduseofTemplateFieldsisindisplayingmetadataabouttheGridView'sunderlyingdata.Inadditionto
showingtheemployees'hiredates,forexample,wemightalsowanttohaveacolumnthatdisplayshowmany
totaldaysthey'vebeenonthejob.
YetanotheruseofTemplateFieldsarisesinscenarioswhentheunderlyingdataneedstobedisplayed
differentlyinthewebpagereportthanintheformatit'sstoredinthedatabase.ImaginethattheEmployees
tablehadaGender fieldthatstoredthecharacterM orF toindicatethesexoftheemployee.Whendisplaying
thisinformationinawebpagewemightwanttoshowthegenderaseither"Male"or"Female",asopposedto
just"M"or"F".
BothofthesescenarioscanbehandledbycreatingaformattingmethodintheASP.NETpage'scodebehind
class(orinaseparateclasslibrary,implementedasastatic method)thatisinvokedfromthetemplate.Such
aformattingmethodisinvokedfromthetemplateusingthesamedatabindingsyntaxseenearlier.The
formattingmethodcantakeinanynumberofparameters,butmustreturnastring.Thisreturnedstringisthe
HTMLthatisinjectedintothetemplate.
Toillustratethisconcept,let'saugmentourtutorialtoshowacolumnthatliststhetotalnumberofdaysan
employeehasbeenonthejob.ThisformattingmethodwilltakeinaNorthwind.EmployeesRow objectand
returnthenumberofdaystheemployeehasbeenemployedasastring.Thismethodcanbeaddedtothe
ASP.NETpage'scodebehindclass,butmustbemarkedasprotected orpublic inordertobeaccessible
fromthetemplate.
protectedstringDisplayDaysOnJob(Northwind.EmployeesRowemployee)
{
//MakesureHiredDateisnotnull...ifso,return"Unknown"
if(employee.IsHireDateNull())
return"Unknown"
else
{
//Returnsthenumberofdaysbetweenthecurrent
//date/timeandHireDate
TimeSpants=DateTime.Now.Subtract(employee.HireDate)
returnts.Days.ToString("#,##0")
}
}
14of17
Figure15:AddaNewTemplateFieldtotheGridView
SetthisnewTemplateField'sHeaderText propertyto"DaysontheJob"anditsItemStyle's
HorizontalAlign propertyto Center.TocalltheDisplayDaysOnJob methodfromthetemplate,addan
ItemTemplate andusethefollowingdatabindingsyntax:
<%#DisplayDaysOnJob((Northwind.EmployeesRow)
((System.Data.DataRowView)Container.DataItem).Row)%>
Container.DataItem returnsaDataRowView objectcorrespondingtotheDataSource recordboundtothe
GridViewRow.ItsRow propertyreturnsthestronglytypedNorthwind.EmployeesRow,whichispassedtothe
DisplayDaysOnJob method.ThisdatabindingsyntaxcanappeardirectlyintheItemTemplate (asshownin
thedeclarativesyntaxbelow)orcanbeassignedtotheText propertyofaLabelWebcontrol.
15of17
<Columns>
<asp:TemplateFieldHeaderText="Name"
SortExpression="FirstName">
<EditItemTemplate>
<asp:TextBoxID="TextBox1"runat="server"
Text='<%#Bind("FirstName")%>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:LabelID="Label1"runat="server"
Text='<%#Bind("FirstName")%>'></asp:Label>
<asp:LabelID="Label2"runat="server"
Text='<%#Eval("LastName")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundFieldDataField="Title"HeaderText="Title"
SortExpression="Title"/>
<asp:TemplateFieldHeaderText="HireDate"
SortExpression="HireDate">
<EditItemTemplate>
<asp:TextBoxID="TextBox2"runat="server"
Text='<%#Bind("HireDate")%>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:CalendarID="Calendar1"runat="server"
SelectedDate='<%#Bind("HireDate")%>'
VisibleDate='<%#Eval("HireDate")%>'>
</asp:Calendar>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateFieldHeaderText="DaysOnTheJob">
<ItemTemplate>
<%#DisplayDaysOnJob((Northwind.EmployeesRow)
((System.Data.DataRowView)Container.DataItem).Row)%>
</ItemTemplate>
<ItemStyleHorizontalAlign="Center"/>
</asp:TemplateField>
</Columns>
</asp:GridView>
Figure16showsthecompletedtutorial,whenviewedthroughabrowser.
16of17
Figure16:TheNumberofDaystheEmployeeHasBeenontheJobisDisplayed
Summary
TheTemplateFieldintheGridViewcontrolallowsforahigherdegreeofflexibilityindisplayingdatathanis
availablewiththeotherfieldcontrols.TemplateFieldsareidealforsituationswhere:
MultipledatafieldsneedtobedisplayedinoneGridViewcolumn
ThedataisbestexpressedusingaWebcontrolratherthanplaintext
Theoutputdependsontheunderlyingdata,suchasdisplayingmetadataorinreformattingthedata
Inadditiontocustomizingthedisplayofdata,TemplateFieldsarealsousedforcustomizingtheuserinterfaces
usedforeditingandinsertingdata,aswe'llseeinfuturetutorials.
Thenexttwotutorialscontinueexploringtemplates,startingwithalookatusingTemplateFieldsina
DetailsView.Followingthat,we'llturntotheFormView,whichusestemplatesinlieuoffieldstoprovide
greaterflexibilityinthelayoutandstructureofthedata.
HappyProgramming!
Clickhereforthenexttutorial
AbouttheAuthor
ScottMitchell,authorofsixASP/ASP.NETbooksandfounderof4GuysFromRolla.com,hasbeenworking
17of17
withMicrosoftWebtechnologiessince1998.Scottworksasanindependentconsultant,trainer,andwriter,
recentlycompletinghislatestbook,SamsTeachYourselfASP.NET2.0in24Hours.Hecanbereachedat
[email protected] orviahisblog,whichcanbefoundathttp://ScottOnWriting.NET.
SpecialThanksTo
Thistutorialserieswasreviewedbymanyhelpfulreviewers.LeadreviewerforthistutorialwasDanJagers.
InterestedinreviewingmyupcomingMSDNarticles?Ifso,[email protected].