Download - Data Tutorial 12 Cs

Transcript
  • 1of17

    Thistutorialispartofaset.FindoutmoreaboutdataaccesswithASP.NETintheWorkingwithDatainASP.NET2.0sectionoftheASP.NETsiteathttp://www.asp.net/learn/dataaccess/default.aspx.

    WorkingwithDatainASP.NET2.0::UsingTemplateFieldsintheGridViewControlDownloadthecodeforthissample

    Clickherefortheprevioustutorial

    IntroductionTheGridViewiscomposedofasetoffieldsthatindicatewhatpropertiesfromtheDataSourcearetobeincludedintherenderedoutputalongwithhowthedatawillbedisplayed.ThesimplestfieldtypeistheBoundField,whichdisplaysadatavalueastext.OtherfieldtypesdisplaythedatausingalternateHTMLelements.TheCheckBoxField,forexample,rendersasacheckboxwhosecheckedstatedependsonthevalueofaspecifieddatafieldtheImageFieldrendersanimagewhoseimagesourceisbaseduponaspecifieddatafield.HyperlinksandbuttonswhosestatedependsonanunderlyingdatafieldvaluecanberenderedusingtheHyperLinkFieldandButtonFieldfieldtypes.

    WhiletheCheckBoxField,ImageField,HyperLinkField,andButtonFieldfieldtypesallowforanalternateviewofthedata,theystillarefairlylimitedwithrespecttoformatting.ACheckBoxFieldcanonlydisplayasinglecheckbox,whereasanImageFieldcanonlydisplayasingleimage.Whatifaparticularfieldneedstodisplaysometext,acheckbox,andanimage,allbasedupondifferentdatafieldvalues?OrwhatifwewantedtodisplaythedatausingaWebcontrolotherthantheCheckBox,Image,HyperLink,orButton?Furthermore,theBoundFieldlimitsitsdisplaytoasingledatafield.WhatifwewantedtoshowtwoormoredatafieldvaluesinasingleGridViewcolumn?

    ToaccommodatethislevelofflexibilitytheGridViewofferstheTemplateField,whichrendersusingatemplate.AtemplatecanincludeamixofstaticHTML,Webcontrols,anddatabindingsyntax.Furthermore,theTemplateFieldhasavarietyoftemplatesthatcanbeusedtocustomizetherenderingfordifferentsituations.Forexample,theItemTemplateisusedbydefaulttorenderthecellforeachrow,buttheEditItemTemplatetemplatecanbeusedtocustomizetheinterfacewheneditingdata.

    Inthistutorialwe'llexaminehowtousetheTemplateFieldtoachieveagreaterdegreeofcustomizationwiththeGridViewcontrol.Intheprecedingtutorial wesawhowtocustomizetheformattingbasedontheunderlyingdatausingtheDataBoundandRowDataBoundeventhandlers.Anotherwaytocustomizetheformattingbasedontheunderlyingdataisbycallingformattingmethodsfromwithinatemplate.We'lllookatthistechniqueinthistutorialaswell.

    ForthistutorialwewilluseTemplateFieldstocustomizetheappearanceofalistofemployees.Specifically,we'lllistalloftheemployees,butwilldisplaytheemployee'sfirstandlastnamesinonecolumn,theirhiredateinaCalendarcontrol,andastatuscolumnthatindicateshowmanydaysthey'vebeenemployedatthecompany.

  • 2of17

    Figure1:ThreeTemplateFieldsareUsedtoCustomizetheDisplay

    Step1:BindingtheDatatotheGridViewInreportingscenarioswhereyouneedtouseTemplateFieldstocustomizetheappearance,IfinditeasiesttostartbycreatingaGridViewcontrolthatcontainsjustBoundFieldsfirstandthentoaddnewTemplateFieldsorconverttheexistingBoundFieldstoTemplateFieldsasneeded.Therefore,let'sstartthistutorialbyaddingaGridViewtothepagethroughtheDesignerandbindingittoanObjectDataSourcethatreturnsthelistofemployees.ThesestepswillcreateaGridViewwithBoundFieldsforeachoftheemployeefields.

    OpentheGridViewTemplateField.aspxpageanddragaGridViewfromtheToolboxontotheDesigner.FromtheGridView'ssmarttagchoosetoaddanewObjectDataSourcecontrolthatinvokestheEmployeesBLLclass'sGetEmployees()method.

  • 3of17

    Figure2:AddaNewObjectDataSourceControlthatInvokestheGetEmployees()Method

    BindingtheGridViewinthismannerwillautomaticallyaddaBoundFieldforeachoftheemployeeproperties:EmployeeID,LastName,FirstName,Title,HireDate,ReportsTo,andCountry.Forthisreportlet'snotbotherwithdisplayingtheEmployeeID,ReportsTo,orCountryproperties.ToremovetheseBoundFieldsyoucan:

    UsetheFieldsdialogboxclickontheEditColumnslinkfromtheGridView'ssmarttagtobringupthisdialogbox.Next,selecttheBoundFieldsfromthelowerleftlistandclicktheredXbuttontoremovetheBoundField.EdittheGridView'sdeclarativesyntaxbyhandfromtheSourceview,deletetheelementfortheBoundFieldyouwishtoremove.

    AfteryouhaveremovedtheEmployeeID,ReportsTo,andCountryBoundFields,yourGridView'smarkupshouldlooklike:

    Takeamomenttoviewourprogressinabrowser.Atthispointyoushouldseeatablewitharecordforeachemployeeandfourcolumns:onefortheemployee'slastname,onefortheirfirstname,onefortheirtitle,andonefortheirhiredate.

  • 4of17

    Figure3:TheLastName,FirstName,Title,andHireDateFieldsareDisplayedforEachEmployee

    Step2:DisplayingtheFirstandLastNamesinaSingleColumnCurrently,eachemployee'sfirstandlastnamesaredisplayedinaseparatecolumn.Itmightbenicetocombinethemintoasinglecolumninstead.ToaccomplishthisweneedtouseaTemplateField.WecaneitheraddanewTemplateField,addtoittheneededmarkupanddatabindingsyntax,andthendeletetheFirstNameandLastNameBoundFields,orwecanconverttheFirstNameBoundFieldintoaTemplateField,edittheTemplateFieldtoincludetheLastNamevalue,andthenremovetheLastNameBoundField.

    Bothapproachesnetthesameresult,butpersonallyIlikeconvertingBoundFieldstoTemplateFieldswhenpossiblebecausetheconversionautomaticallyaddsanItemTemplateandEditItemTemplatewithWebcontrolsanddatabindingsyntaxtomimictheappearanceandfunctionalityoftheBoundField.Thebenefitisthatwe'llneedtodolessworkwiththeTemplateFieldastheconversionprocesswillhaveperformedsomeoftheworkforus.

    ToconvertanexistingBoundFieldintoaTemplateField,clickontheEditColumnslinkfromtheGridView'ssmarttag,bringinguptheFieldsdialogbox.SelecttheBoundFieldtoconvertfromthelistinthelowerleftcornerandthenclickthe"ConvertthisfieldintoaTemplateField"linkinthebottomrightcorner.

  • 5of17

    Figure4:ConvertaBoundFieldIntoaTemplateFieldfromtheFieldsDialogBox

    GoaheadandconverttheFirstNameBoundFieldintoaTemplateField.Afterthischangethere'snoperceptivedifferenceintheDesigner.ThisisbecauseconvertingtheBoundFieldintoaTemplateFieldcreatesaTemplateFieldthatmaintainsthelookandfeeloftheBoundField.DespitetherebeingnovisualdifferenceatthispointintheDesigner,thisconversionprocesshasreplacedtheBoundField'sdeclarativesyntaxwiththefollowingTemplateFieldsyntax:

    Asyoucansee,theTemplateFieldconsistsoftwotemplatesanItemTemplatethathasaLabelwhoseTextpropertyissettothevalueoftheFirstNamedatafield,andanEditItemTemplatewithaTextBoxcontrolwhoseTextpropertyisalsosettotheFirstNamedatafield.ThedatabindingsyntaxindicatesthatthedatafieldfieldNameisboundtothespecifiedWebcontrolproperty.

    ToaddtheLastNamedatafieldvaluetothisTemplateFieldweneedtoaddanotherLabelWebcontrolintheItemTemplateandbinditsTextpropertytoLastName.ThiscanbeaccomplishedeitherbyhandorthroughtheDesigner.Todoitbyhand,simplyaddtheappropriatedeclarativesyntaxtotheItemTemplate:

  • 6of17

    ToadditthroughtheDesigner,clickontheEditTemplateslinkfromtheGridView'ssmarttag.ThiswilldisplaytheGridView'stemplateeditinginterface.Inthisinterface'ssmarttagisalistofthetemplatesintheGridView.SinceweonlyhaveoneTemplateFieldatthispoint,theonlytemplateslistedinthedropdownlistarethosetemplatesfortheFirstNameTemplateFieldalongwiththeEmptyDataTemplateandPagerTemplate.TheEmptyDataTemplatetemplate,ifspecified,isusedtorendertheGridView'soutputiftherearenoresultsinthedataboundtotheGridViewthePagerTemplate,ifspecified,isusedtorenderthepaginginterfaceforaGridViewthatsupportspaging.

    Figure5:TheGridView'sTemplatesCanBeEditedThroughtheDesigner

    ToalsodisplaytheLastNameintheFirstNameTemplateFielddragtheLabelcontrolfromtheToolboxintotheFirstNameTemplateField'sItemTemplateintheGridView'stemplateeditinginterface.

  • 7of17

    Figure6:AddaLabelWebControltotheFirstNameTemplateField'sItemTemplate

    AtthispointtheLabelWebcontroladdedtotheTemplateFieldhasitsTextpropertysetto"Label".WeneedtochangethissothatthispropertyisboundtothevalueoftheLastNamedatafieldinstead.ToaccomplishthisclickontheLabelcontrol'ssmarttagandchoosetheEditDataBindingsoption.

    Figure7:ChoosetheEditDataBindingsOptionfromtheLabel'sSmartTag

    ThiswillbringuptheDataBindingsdialogbox.Fromhereyoucanselectthepropertytoparticipateindatabindingfromthelistontheleftandchoosethefieldtobindthedatatofromthedropdownlistontheright.ChoosetheTextpropertyfromtheleftandtheLastNamefieldfromtherightandclickOK.

  • 8of17

    Figure8:BindtheTextPropertytotheLastNameDataField

    Note:TheDataBindingsdialogboxallowsyoutoindicatewhethertoperformtwowaydatabinding.Ifyouleavethisunchecked,thedatabindingsyntaxwillbeusedinsteadof.Eitherapproachisfineforthistutorial.Twowaydatabindingbecomesimportantwheninsertingandeditingdata.Forsimplydisplayingdata,however,eitherapproachwillworkequallywell.We'lldiscusstwowaydatabindingindetailinfuturetutorials.

    Takeamomenttoviewthispagethroughabrowser.Asyoucansee,theGridViewstillincludesfourcolumnshowever,theFirstNamecolumnnowlistsboththeFirstNameandLastNamedatafieldvalues.

    Figure9:BoththeFirstNameandLastNameValuesareShowninaSingleColumn

    Tocompletethisfirststep,removetheLastNameBoundFieldandrenametheFirstNameTemplateField'sHeaderTextpropertyto"Name".AfterthesechangestheGridView'sdeclarativemarkupshouldlooklikethefollowing:

  • 9of17

    Figure10:EachEmployee'sFirstandLastNamesareDisplayedinOneColumn

    Step3:UsingtheCalendarControltoDisplaytheHiredDateField

    DisplayingadatafieldvalueastextinaGridViewisassimpleasusingaBoundField.Forcertainscenarios,however,thedataisbestexpressedusingaparticularWebcontrolinsteadofjusttext.SuchcustomizationofthedisplayofdataispossiblewithTemplateFields.Forexample,ratherthandisplaytheemployee'shiredateastext,wecouldshowacalendar(usingtheCalendarcontrol)withtheirhiredatehighlighted.

    Toaccomplishthis,startbyconvertingtheHiredDateBoundFieldintoaTemplateField.SimplygototheGridView'ssmarttagandclicktheEditColumnslink,bringinguptheFieldsdialogbox.SelecttheHiredDateBoundFieldandclick"ConvertthisfieldintoaTemplateField."

  • 10of17

    Figure11:ConverttheHiredDateBoundFieldIntoaTemplateField

    AswesawinStep2,thiswillreplacetheBoundFieldwithaTemplateFieldthatcontainsanItemTemplateandEditItemTemplatewithaLabelandTextBoxwhoseTextpropertiesareboundtotheHiredDatevalueusingthedatabindingsyntax.

    ToreplacethetextwithaCalendarcontrol,editthetemplatebyremovingtheLabelandaddingaCalendarcontrol.FromtheDesigner,selectEditTemplatesfromtheGridView'ssmarttagandchoosetheHireDateTemplateField'sItemTemplatefromthedropdownlist.Next,deletetheLabelcontrolanddragaCalendarcontrolfromtheToolboxintothetemplateeditinginterface.

  • 11of17

    Figure12:AddaCalendarControltotheHireDateTemplateField'sItemTemplate

    AtthispointeachrowintheGridViewwillcontainaCalendarcontrolinitsHiredDateTemplateField.However,theemployee'sactualHiredDatevalueisnotsetanywhereintheCalendarcontrol,causingeachCalendarcontroltodefaulttoshowingthecurrentmonthanddate.Toremedythis,weneedtoassigneachemployee'sHiredDatetotheCalendarcontrol'sSelectedDateandVisibleDateproperties.

    FromtheCalendarcontrol'ssmarttag,chooseEditDataBindings.Next,bindbothSelectedDateandVisibleDatepropertiestotheHiredDatedatafield.

    Figure13:BindtheSelectedDateandVisibleDatePropertiestotheHiredDateDataField

  • 12of17

    Note:TheCalendarcontrol'sselecteddateneednotnecessarilybevisible.Forexample,aCalendarmayhave

    August1st,1999astheselecteddate,butbeshowingthecurrentmonthandyear.TheselecteddateandvisibledatearespecifiedbytheCalendarcontrol'sSelectedDateandVisibleDateproperties.Sincewewanttobothselecttheemployee'sHiredDateandmakesurethatit'sshownweneedtobindbothofthesepropertiestotheHireDatedatafield.

    Whenviewingthepageinabrowser,thecalendarnowshowsthemonthoftheemployee'shireddateandselectsthatparticulardate.

    Figure14:TheEmployee'sHiredDateisShownintheCalendarControl

    Note:Contrarytoalltheexampleswe'veseenthusfar,forthistutorialwedidnotsetEnableViewStatepropertytofalseforthisGridView.ThereasonforthisdecisionisbecauseclickingthedatesoftheCalendarcontrolcausesapostback,settingtheCalendar'sselecteddatetothedatejustclicked.IftheGridView'sviewstateisdisabled,however,oneachpostbacktheGridView'sdataisreboundtoitsunderlyingdatasource,whichcausestheCalendar'sselecteddatetobesetbacktotheemployee'sHireDate,overwritingthedatechosenbytheuser.

    Forthistutorialthisisamootdiscussionsincetheuserisnotabletoupdatetheemployee'sHireDate.ItwouldprobablybebesttoconfiguretheCalendarcontrolsothatitsdatesarenotselectable.Regardless,thistutorialshowsthatinsomecircumstancesviewstatemustbeenabledinordertoprovidecertainfunctionality.

    Step4:ShowingtheNumberofDaystheEmployeeHasWorkedfortheCompany

  • 13of17

    SofarwehaveseentwoapplicationsofTemplateFields:

    Combiningtwoormoredatafieldvaluesintoonecolumn,andExpressingadatafieldvalueusingaWebcontrolinsteadoftext

    AthirduseofTemplateFieldsisindisplayingmetadataabouttheGridView'sunderlyingdata.Inadditiontoshowingtheemployees'hiredates,forexample,wemightalsowanttohaveacolumnthatdisplayshowmanytotaldaysthey'vebeenonthejob.

    YetanotheruseofTemplateFieldsarisesinscenarioswhentheunderlyingdataneedstobedisplayeddifferentlyinthewebpagereportthanintheformatit'sstoredinthedatabase.ImaginethattheEmployeestablehadaGenderfieldthatstoredthecharacterMorFtoindicatethesexoftheemployee.Whendisplayingthisinformationinawebpagewemightwanttoshowthegenderaseither"Male"or"Female",asopposedtojust"M"or"F".

    BothofthesescenarioscanbehandledbycreatingaformattingmethodintheASP.NETpage'scodebehindclass(orinaseparateclasslibrary,implementedasastaticmethod)thatisinvokedfromthetemplate.Suchaformattingmethodisinvokedfromthetemplateusingthesamedatabindingsyntaxseenearlier.Theformattingmethodcantakeinanynumberofparameters,butmustreturnastring.ThisreturnedstringistheHTMLthatisinjectedintothetemplate.

    Toillustratethisconcept,let'saugmentourtutorialtoshowacolumnthatliststhetotalnumberofdaysanemployeehasbeenonthejob.ThisformattingmethodwilltakeinaNorthwind.EmployeesRowobjectandreturnthenumberofdaystheemployeehasbeenemployedasastring.ThismethodcanbeaddedtotheASP.NETpage'scodebehindclass,butmustbemarkedasprotectedorpublicinordertobeaccessiblefromthetemplate.

    protectedstringDisplayDaysOnJob(Northwind.EmployeesRowemployee){

    //MakesureHiredDateisnotnull...ifso,return"Unknown"if(employee.IsHireDateNull())

    return"Unknown"else{

    //Returnsthenumberofdaysbetweenthecurrent//date/timeandHireDateTimeSpants=DateTime.Now.Subtract(employee.HireDate)returnts.Days.ToString("#,##0")

    }}

    SincetheHiredDatefieldcancontainNULLdatabasevalueswemustfirstensurethatthevalueisnotNULLbeforeproceedingwiththecalculation.IftheHiredDatevalueisNULL,wesimplyreturnthestring"Unknown"ifitisnotNULL,wecomputethedifferencebetweenthecurrenttimeandtheHiredDatevalueandreturnthenumberofdays.

    ToutilizethismethodweneedtoinvokeitfromaTemplateFieldintheGridViewusingthedatabindingsyntax.StartbyaddinganewTemplateFieldtotheGridViewbyclickingontheEditColumnslinkintheGridView'ssmarttagandaddinganewTemplateField.

  • 14of17

    Figure15:AddaNewTemplateFieldtotheGridView

    SetthisnewTemplateField'sHeaderTextpropertyto"DaysontheJob"anditsItemStyle'sHorizontalAlignpropertytoCenter.TocalltheDisplayDaysOnJobmethodfromthetemplate,addanItemTemplateandusethefollowingdatabindingsyntax:

    Container.DataItemreturnsaDataRowViewobjectcorrespondingtotheDataSourcerecordboundtotheGridViewRow.ItsRowpropertyreturnsthestronglytypedNorthwind.EmployeesRow,whichispassedtotheDisplayDaysOnJobmethod.ThisdatabindingsyntaxcanappeardirectlyintheItemTemplate(asshowninthedeclarativesyntaxbelow)orcanbeassignedtotheTextpropertyofaLabelWebcontrol.

    Note:Alternatively,insteadofpassinginanEmployeesRowinstance,wecouldjustpassintheHireDatevalueusing.However,theEvalmethodreturnsanobject,sowe'dhavetochangeourDisplayDaysOnJobmethodsignaturetoacceptaninputparameteroftypeobject,instead.Wecan'tblindlycasttheEval("HireDate")calltoaDateTimebecausetheHireDatecolumnintheEmployeestablecancontainNULLvalues.Therefore,we'dneedtoacceptanobjectastheinputparameterfortheDisplayDaysOnJobmethod,checktoseeifithadadatabaseNULLvalue(whichcanbeaccomplishedusingConvert.IsDBNull(objectToCheck)),andthenproceedaccordingly.

    Duetothesesubtleties,I'veoptedtopassintheentireEmployeesRowinstance.Inthenexttutorialwe'llseeamorefittingexampleforusingtheEval("columnName")syntaxforpassinganinputparameterintoaformattingmethod.

    ThefollowingshowsthedeclarativesyntaxforourGridViewaftertheTemplateFieldhasbeenaddedandtheDisplayDaysOnJobmethodcalledfromtheItemTemplate:

  • 15of17

    Figure16showsthecompletedtutorial,whenviewedthroughabrowser.

  • 16of17

    Figure16:TheNumberofDaystheEmployeeHasBeenontheJobisDisplayed

    SummaryTheTemplateFieldintheGridViewcontrolallowsforahigherdegreeofflexibilityindisplayingdatathanisavailablewiththeotherfieldcontrols.TemplateFieldsareidealforsituationswhere:

    MultipledatafieldsneedtobedisplayedinoneGridViewcolumnThedataisbestexpressedusingaWebcontrolratherthanplaintextTheoutputdependsontheunderlyingdata,suchasdisplayingmetadataorinreformattingthedata

    Inadditiontocustomizingthedisplayofdata,TemplateFieldsarealsousedforcustomizingtheuserinterfacesusedforeditingandinsertingdata,aswe'llseeinfuturetutorials.

    Thenexttwotutorialscontinueexploringtemplates,startingwithalookatusingTemplateFieldsinaDetailsView.Followingthat,we'llturntotheFormView,whichusestemplatesinlieuoffieldstoprovidegreaterflexibilityinthelayoutandstructureofthedata.

    HappyProgramming!

    Clickhereforthenexttutorial

    AbouttheAuthorScottMitchell,authorofsixASP/ASP.NETbooksandfounderof4GuysFromRolla.com,hasbeenworking

  • 17of17

    withMicrosoftWebtechnologiessince1998.Scottworksasanindependentconsultant,trainer,andwriter,recentlycompletinghislatestbook,SamsTeachYourselfASP.NET2.0in24Hours.Hecanbereachedatmitchell@4guysfromrolla.com orviahisblog,whichcanbefoundathttp://ScottOnWriting.NET.

    SpecialThanksToThistutorialserieswasreviewedbymanyhelpfulreviewers.LeadreviewerforthistutorialwasDanJagers.InterestedinreviewingmyupcomingMSDNarticles?Ifso,[email protected].


Top Related