data tutorial 12 cs

17
1 of 17 This tutorial is part of a set. Find out more about data access with ASP.NET in the Working with Data in ASP.NET 2.0 section of the ASP.NET site at http://www.asp.net/learn/dataaccess/default.aspx. Working with Data in ASP.NET 2.0 :: Using TemplateFields in the GridView Control Download the code for this sample Click here for the previous tutorial Introduction The GridView is composed of a set of fields that indicate what properties from the DataSource are to be included in the rendered output along with how the data will be displayed. The simplest field type is the BoundField, which displays a data value as text. Other field types display the data using alternate HTML elements. The CheckBoxField, for example, renders as a checkbox whose checked state depends on the value of a specified data field; the ImageField renders an image whose image source is based upon a specified data field. Hyperlinks and buttons whose state depends on an underlying data field value can be rendered using the HyperLinkField and ButtonField field types. While the CheckBoxField, ImageField, HyperLinkField, and ButtonField field types allow for an alternate view of the data, they still are fairly limited with respect to formatting. A CheckBoxField can only display a single checkbox, whereas an ImageField can only display a single image. What if a particular field needs to display some text, a checkbox, and an image, all based upon different data field values? Or what if we wanted to display the data using a Web control other than the CheckBox, Image, HyperLink, or Button? Furthermore, the BoundField limits its display to a single data field. What if we wanted to show two or more data field values in a single GridView column? To accommodate this level of flexibility the GridView offers the TemplateField, which renders using a template. A template can include a mix of static HTML, Web controls, and databinding syntax. Furthermore, the TemplateField has a variety of templates that can be used to customize the rendering for different situations. For example, the ItemTemplate is used by default to render the cell for each row, but the EditItemTemplate template can be used to customize the interface when editing data. In this tutorial we'll examine how to use the TemplateField to achieve a greater degree of customization with the GridView control. In the preceding tutorial we saw how to customize the formatting based on the underlying data using the DataBound and RowDataBound event handlers. Another way to customize the formatting based on the underlying data is by calling formatting methods from within a template. We'll look at this technique in this tutorial as well. For this tutorial we will use TemplateFields to customize the appearance of a list of employees. Specifically, we'll list all of the employees, but will display the employee's first and last names in one column, their hire date in a Calendar control, and a status column that indicates how many days they've been employed at the company.

Upload: van-bao-nguyen

Post on 14-Nov-2015

217 views

Category:

Documents


1 download

DESCRIPTION

...

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].