You are on page 1of 8

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

WorkingwithDatainASP.NET2.0:: ProgrammaticallySettingtheObjectDataSource's ParameterValues


Introduction Aswesawintheprevioustutorial,anumberofoptionsareavailablefordeclarativelypassingparameter valuestotheObjectDataSource'smethods.Iftheparametervalueishardcoded,comesfromaWebcontrol onthepage,orisinanyothersourcethatisreadablebyadatasourceParameter object,forexample,that valuecanbeboundtotheinputparameterwithoutwritingalineofcode. Theremaybetimes,however,whentheparametervaluecomesfromsomesourcenotalreadyaccountedfor byoneofthebuiltindatasourceParameter objects.Ifoursitesupporteduseraccountswemightwanttoset theparameterbasedonthecurrentlyloggedinvisitor'sUserID.Orwemayneedtocustomizetheparameter valuebeforesendingitalongtotheObjectDataSource'sunderlyingobject'smethod. WhenevertheObjectDataSource'sSelect methodisinvokedtheObjectDataSourcefirstraisesitsSelecting event.TheObjectDataSource'sunderlyingobject'smethodistheninvoked.Oncethatcompletesthe ObjectDataSource'sSelectedeventfires(Figure1illustratesthissequenceofevents).Theparametervalues passedintotheObjectDataSource'sunderlyingobject'smethodcanbesetorcustomizedinaneventhandler fortheSelecting event.

Figure1:TheObjectDataSource'sSelected andSelecting EventsFireBeforeandAfterIts UnderlyingObject'sMethodisInvoked Inthistutorialwe'lllookataddingamethodtoourDALandBLLthatacceptsasingleinputparameter Month,oftypeint andreturnsanEmployeesDataTable objectpopulatedwiththoseemployeesthathave

1of8

theirhiringanniversaryinthespecifiedMonth.Ourexamplewillsetthisparameterprogrammaticallybasedon thecurrentmonth,showingalistof"EmployeeAnniversariesThisMonth." Let'sgetstarted! Step1:AddingaMethodtoEmployeesTableAdapter ForourfirstexampleweneedtoaddameanstoretrievethoseemployeeswhoseHireDate occurredina specifiedmonth.Toprovidethisfunctionalityinaccordancewithourarchitectureweneedtofirstcreatea methodinEmployeesTableAdapter thatmapstotheproperSQLstatement.Toaccomplishthis,startby openingtheNorthwindTypedDataSet.RightclickontheEmployeesTableAdapter labelandchooseAdd Query.

Figure2:AddaNewQuerytotheEmployeesTableAdapter ChoosetoaddaSQLstatementthatreturnsrows.WhenyoureachtheSpecifyaSELECT Statementscreenthe default SELECT statementfortheEmployeesTableAdapter willalreadybeloaded.SimplyaddintheWHERE clause:WHEREDATEPART(m,HireDate)=@Month.DATEPARTisaTSQLfunctionthatreturnsa particulardateportionofadatetime typeinthiscasewe'reusingDATEPART toreturnthemonthofthe HireDate column.

2of8

Figure3:ReturnOnlyThoseRowsWheretheHireDate ColumnisLessThanorEqualtothe @HiredBeforeDate Parameter Finally,changetheFillBy andGetDataBy methodnamesto FillByHiredDateMonth and GetEmployeesByHiredDateMonth,respectively.

Figure4:ChooseMoreAppropriateMethodNamesThanFillBy andGetDataBy ClickFinishtocompletethewizardandreturntotheDataSet'sdesignsurface.TheEmployeesTableAdapter shouldnowincludeanewsetofmethodsforaccessingemployeeshiredinaspecifiedmonth.

3of8

Figure5:TheNewMethodsAppearintheDataSet'sDesignSurface Step2:AddingtheGetEmployeesByHiredDateMonth(month) MethodtotheBusinessLogicLayer Sinceourapplicationarchitectureusesaseparatelayerforthebusinesslogicanddataaccesslogic,weneedto addamethodtoourBLLthatcallsdowntotheDALtoretrieveemployeeshiredbeforeaspecifieddate. OpentheEmployeesBLL.cs fileandaddthefollowingmethod:


[System.ComponentModel.DataObjectMethodAttribute( System.ComponentModel.DataObjectMethodType.Select,false)] publicNorthwind.EmployeesDataTable GetEmployeesByHiredDateMonth(intmonth) { returnAdapter.GetEmployeesByHiredDateMonth(month) }

Aswithourothermethodsinthisclass,GetEmployeesByHiredDateMonth(month) simplycallsdowninto theDALandreturnstheresults. Step3:DisplayingEmployeesWhoseHiringAnniversaryIsThisMonth Ourfinalstepforthisexampleistodisplaythoseemployeeswhosehiringanniversaryisthismonth.Startby addingaGridViewtotheProgrammaticParams.aspx pageintheBasicReporting folderandaddanew ObjectDataSourceasitsdatasource.ConfiguretheObjectDataSourcetousetheEmployeesBLL classwiththe SelectMethod setto GetEmployeesByHiredDateMonth(month).

4of8

Figure6:UsetheEmployeesBLL Class

Figure7:SelectFromtheGetEmployeesByHiredDateMonth(month) method Thefinalscreenasksustoprovidethemonth parametervalue'ssource.Sincewe'llsetthisvalue programmatically,leavetheParametersourcesettothedefaultNoneoptionandclickFinish.

5of8

Figure8:LeavetheParameterSourceSettoNone ThiswillcreateaParameter objectintheObjectDataSource'sSelectParameters collectionthatdoesnot haveavaluespecified.


<asp:ObjectDataSourceID="ObjectDataSource1"runat="server" OldValuesParameterFormatString="original_{0}" SelectMethod="GetEmployeesByHiredDateMonth" TypeName="EmployeesBLL"> <SelectParameters> <asp:ParameterName="month"Type="Int32"/> </SelectParameters> </asp:ObjectDataSource>

Tosetthisvalueprogrammatically,weneedtocreateaneventhandlerfortheObjectDataSource'sSelecting event.Toaccomplishthis,gototheDesignviewanddoubleclicktheObjectDataSource.Alternatively,select theObjectDataSource,gotothePropertieswindow,andclickthelightningbolticon.Next,either doubleclickinthetextboxnexttotheSelecting eventortypeinthenameoftheeventhandleryouwantto use.

6of8

Figure9:ClickontheLightningBoltIconinthePropertiesWindowtoListaWebControl'sEvents BothapproachesaddaneweventhandlerfortheObjectDataSource'sSelecting eventtothepage's codebehindclass.Inthiseventhandlerwecanreadandwritetotheparametervaluesusing e.InputParameters[parameterName],whereparameterName isthevalueoftheName attributeinthe <asp:Parameter> tag(theInputParameters collectioncanalsobeindexedordinally,asin e.InputParameters[index]).Tosetthemonth parametertothecurrentmonth,addthefollowingtothe Selecting eventhandler:
protectedvoidObjectDataSource1_Selecting(objectsender, ObjectDataSourceSelectingEventArgse) { e.InputParameters["month"]=DateTime.Now.Month }

Whenvisitingthispagethroughabrowserwecanseethatonlyoneemployeewashiredthismonth(March) LauraCallahan,who'sbeenwiththecompanysince1994.

7of8

Figure10:ThoseEmployeesWhoseAnniversariesThisMonthAreShown Summary WhiletheObjectDataSource'sparameters'valuescantypicallybesetdeclaratively,withoutrequiringalineof code,it'seasytosettheparametervaluesprogrammatically.Allweneedtodoiscreateaneventhandlerfor theObjectDataSource'sSelecting event,whichfiresbeforetheunderlyingobject'smethodisinvoked,and manuallysetthevaluesforoneormoreparametersviatheInputParameters collection. ThistutorialconcludestheBasicReportingsection.Thenexttutorial kicksofftheFilteringandMasterDetails Scenariossection,inwhichwe'lllookattechniquesforallowingthevisitortofilterdataanddrilldownfroma masterreportintoadetailsreport. HappyProgramming! AbouttheAuthor ScottMitchell,authorofsixASP/ASP.NETbooksandfounderof4GuysFromRolla.com,hasbeenworking withMicrosoftWebtechnologiessince1998.Scottworksasanindependentconsultant,trainer,andwriter, recentlycompletinghislatestbook,SamsTeachYourselfASP.NET2.0in24Hours.Hecanbereachedat mitchell@4guysfromrolla.com orviahisblog,whichcanbefoundathttp://ScottOnWriting.NET. SpecialThanksTo Thistutorialserieswasreviewedbymanyhelpfulreviewers.LeadreviewerforthistutorialwasHilton Giesenow.InterestedinreviewingmyupcomingMSDNarticles?Ifso,dropmealineat mitchell@4GuysFromRolla.com.

8of8

You might also like