You are on page 1of 12

Thistutorialispartofaset.FindoutmoreaboutdataaccesswithASP.

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

WorkingwithDatainASP.NET2.0::Inserting,
Updating,andDeletingDatawiththeSqlDataSource
Introduction
Asdiscussedin AnOverviewofInserting,Updating,andDeleting,theGridViewcontrolprovidesbuiltin
updatinganddeletingcapabilities,whiletheDetailsViewandFormViewcontrolsincludeinsertingsupportalong
witheditinganddeletingfunctionality.Thesedatamodificationcapabilitiescanbepluggeddirectlyintoadata
sourcecontrolwithoutalineofcodeneedingtobewritten. AnOverviewofInserting,Updating,andDeleting
examinedusingtheObjectDataSourcetofacilitateinserting,updating,anddeletingwiththeGridView,
DetailsView,andFormViewcontrols.Alternatively,theSqlDataSourcecanbeusedinplaceofthe
ObjectDataSource.
Recallthattosupportinserting,updating,anddeleting,withtheObjectDataSourceweneededtospecifytheobject
layermethodstoinvoketoperformtheinsert,update,ordeleteaction.WiththeSqlDataSource,weneedtoprovide
INSERT,UPDATE,andDELETE SQLstatements(orstoredprocedures)toexecute.Aswellseeinthistutorial,these
statementscanbecreatedmanuallyorcanbeautomaticallygeneratedbytheSqlDataSourcesConfigureData
Sourcewizard.
Note: Sincewevealreadydiscussedtheinserting,editing,anddeletingcapabilitiesoftheGridView,DetailsView,
andFormViewcontrols,thistutorialwillfocusonconfiguringtheSqlDataSourcecontroltosupportthese
operations.IfyouneedtobrushuponimplementingthesefeatureswithintheGridView,DetailsView,and
FormView,returntotheEditing,Inserting,andDeletingDatatutorials,startingwithAnOverviewofInserting,
Updating,andDeleting.

Step1:SpecifyingINSERT,UPDATE,andDELETE Statements
Asweveseeninthepasttwotutorials,toretrievedatafromaSqlDataSourcecontrolweneedtosettwo
properties:
1. ConnectionString,whichspecifieswhatdatabasetosendthequeryto,and
2. SelectCommand,whichspecifiestheadhocSQLstatementorstoredprocedurenametoexecutetoreturnthe
results.
ForSelectCommand valueswithparameters,theparametervaluesarespecifiedviatheSqlDataSources
SelectParameters collectionandcanincludehardcodedvalues,commonparametersourcevalues(querystring
fields,sessionvariables,Webcontrolvalues,andsoon),orcanbeprogrammaticallyassigned.Whenthe
SqlDataSourcecontrolsSelect() methodisinvokedeitherprogrammaticallyorautomaticallyfromadataWeb
control aconnectiontothedatabaseisestablished,theparametervaluesareassignedtothequery,andthe
commandisshuttledofftothedatabase.TheresultsarethenreturnedaseitheraDataSetorDataReader,depending
onthevalueofthecontrolsDataSourceMode property.
Alongwithselectingdata,theSqlDataSourcecontrolcanbeusedtoinsert,update,anddeletedatabysupplying
INSERT,UPDATE,andDELETE SQLstatementsinmuchthesameway.SimplyassigntheInsertCommand,
UpdateCommand,andDeleteCommand propertiestheINSERT,UPDATE,andDELETE SQLstatementstoexecute.If
thestatementshaveparameters(astheymostalwayswill),includethemintheInsertParameters,
UpdateParameters,andDeleteParameters collections.
1 of12

OnceanInsertCommand,UpdateCommand,orDeleteCommand valuehasbeenspecified,theEnableInserting,
EnableEditing, or EnableDeleting optioninthecorrespondingdataWebcontrolssmarttagwillbecome
available.Toillustratethis,letstakeanexamplefromtheQuerying.aspx pagewecreatedintheQueryingData
withtheSqlDataSourceControl tutorialandaugmentittoincludedeletecapabilities.
StartbyopeningtheInsertUpdateDelete.aspx andQuerying.aspx pagesfromtheSqlDataSource folder.
FromtheDesignerontheQuerying.aspx page,selecttheSqlDataSourceandGridViewfromthefirstexample
(theProductsDataSource andGridView1 controls).Afterselectingthetwocontrols,gototheEditmenuand
chooseCopy(orjusthitCtrl+C).Next,gototheDesignerofInsertUpdateDelete.aspx andpasteinthe
controls.AfteryouhavemovedthetwocontrolsovertoInsertUpdateDelete.aspx,testoutthepageina
browser.YoushouldseethevaluesoftheProductID,ProductName,andUnitPrice columnsforalloftherecords
intheProducts databasetable.

Figure1:AlloftheProductsareListed,OrderedbyProductID

AddingtheSqlDataSourcesDeleteCommand andDeleteParameters
Properties
AtthispointwehaveaSqlDataSourcethatsimplyreturnsalloftherecordsfromtheProducts tableanda
GridViewthatrendersthisdata.Ourgoalistoextendthisexampletoallowfortheusertodeleteproductsviathe
GridView.ToaccomplishthisweneedtospecifyvaluesfortheSqlDataSourcecontrolsDeleteCommand and
DeleteParameters propertiesandthenconfiguretheGridViewtosupportdeleting.

2 of12

TheDeleteCommand andDeleteParameters propertiescanbespecifiedinanumberofways:


l
l
l
l

Throughthedeclarativesyntax
FromthePropertieswindowintheDesigner
FromtheSpecifyacustomSQLstatementorstoredprocedurescreenintheConfigureDataSourcewizard
ViatheAdvancedbuttonintheSpecifycolumnsfromatableofviewscreenintheConfigureDataSource
wizard,whichwillactuallyautomaticallygeneratetheDELETE SQLstatementandparametercollectionused
intheDeleteCommand andDeleteParameters properties

WellexaminehowtoautomaticallyhavetheDELETE statementcreatedinStep2.Fornow,letsusetheProperties
windowintheDesigner,althoughtheConfigureDataSourcewizardordeclarativesyntaxoptionwouldworkjust
aswell.
FromtheDesignerinInsertUpdateDelete.aspx,clickontheProductsDataSource SqlDataSourceandthen
bringupthePropertieswindow(fromtheViewmenu,choosePropertieswindow,orsimplyhitF4).Selectthe
DeleteQueryproperty,whichwillbringupasetofellipses.

Figure2:SelecttheDeleteQueryPropertyfromthePropertiesWindow

3 of12

Note: TheSqlDataSourcedoesnthaveaDeleteQueryproperty.Rather,DeleteQueryisacombinationofthe
DeleteCommand andDeleteParameters propertiesandisonlylistedinthePropertieswindowwhenviewingthe
windowthroughtheDesigner.IfyouarelookingatthePropertieswindowintheSourceview,youllfindthe
DeleteCommand propertyinstead.
ClicktheellipsesintheDeleteQuerypropertytobringuptheCommandandParameterEditordialogbox(see
Figure3).FromthisdialogboxyoucanspecifytheDELETE SQLstatementandspecifytheparameters.Enterthe
followingqueryintotheDELETE commandtextbox(eithermanuallyorusingtheQueryBuilder,ifyouprefer):
DELETEFROMProducts
WHEREProductID=@ProductID

Next,clicktheRefreshParametersbuttontoaddthe@ProductID parametertothelistofparametersbelow.

Figure3:SelecttheDeleteQueryPropertyfromthePropertiesWindow
Do not provideavalueforthisparameter(leaveitsParametersourceatNone).Onceweadddeletingsupportto
theGridView,theGridViewwillautomaticallysupplythisparametervalue,usingthevalueofitsDataKeys
collectionfortherowwhoseDeletebuttonwasclicked.
Note: TheparameternameusedintheDELETE querymustbethesameasthenameoftheDataKeyNames valuein
theGridView,DetailsView,orFormView.Thatis,theparameterintheDELETE statementispurposefullynamed
@ProductID (insteadof,say,@ID),becausetheprimarykeycolumnnameintheProductstable(andthereforethe
DataKeyNamesvalueintheGridView)is ProductID.
IftheparameternameandDataKeyNames valuedoesntmatch,theGridViewcannotautomaticallyassignthe
parameterthevaluefromtheDataKeys collection.

4 of12

AfterenteringthedeleterelatedinformationintotheCommandandParameterEditordialogboxclickOKandgo
totheSourceviewtoexaminetheresultingdeclarativemarkup:
<asp:SqlDataSourceID="ProductsDataSource"runat="server"
ConnectionString="<%$ConnectionStrings:NORTHWNDConnectionString%>"
SelectCommand=
"SELECT[ProductID],[ProductName],[UnitPrice]FROM[Products]"
DeleteCommand="DELETEFROMProductsWHEREProductID=@ProductID">
<DeleteParameters>
<asp:ParameterName="ProductID"/>
</DeleteParameters>
</asp:SqlDataSource>

NotetheadditionoftheDeleteCommand propertyaswellasthe<DeleteParameters> sectionandtheParameter


objectnamedproductID.

ConfiguringtheGridViewforDeleting
WiththeDeleteCommand propertyadded,theGridViewssmarttagnowcontainstheEnableDeletingoption.Go
aheadandcheckthischeckbox.AsdiscussedinAnOverviewofInserting,Updating,andDeleting,thiscausesthe
GridViewtoaddaCommandFieldwithitsShowDeleteButton propertysettoTrue.AsFigure4shows,whenthe
pageisvisitedthroughabrowseraDeletebuttonisincluded.Testthispageoutbydeletingsomeproducts.

Figure4:EachGridViewRowNowIncludesaDeleteButton

5 of12

UponclickingaDeletebutton,apostbackoccurs,theGridViewassignstheProductID parameterthevalueofthe
DataKeys collectionvaluefortherowwhoseDeletebuttonwasclicked,andinvokestheSqlDataSourcesDelete
() method.TheSqlDataSourcecontrolthenconnectstothedatabaseandexecutestheDELETE statement.The
GridViewthenrebindstotheSqlDataSource,gettingbackanddisplayingthecurrentsetofproducts(whichno
longerincludesthejustdeletedrecord).
Note: SincetheGridViewusesitsDataKeys collectiontopopulatetheSqlDataSourceparameters,itsvitalthatthe
GridViewsDataKeyNames propertybesettothecolumn(s)thatconstitutetheprimarykeyandthatthe
SqlDataSourcesSelectCommand returnsthesecolumns.Moreover,itsimportantthattheparameternameinthe
SqlDataSourcesDeleteCommand issetto@ProductID.IftheDataKeyNames propertyisnotsetortheparameteris
notnamed@ProductsID,clickingtheDeletebuttonwillcauseapostback,butwontactuallydeleteanyrecord.
Figure5depictsthisinteractiongraphically.ReferbacktotheExaminingtheEventsAssociatedwithInserting,
Updating,andDeleting tutorialforamoredetaileddiscussiononthechainofeventsassociatedwithinserting,
updating,anddeletingfromadataWebcontrol.

Figure5:ClickingtheDeleteButtonintheGridViewInvokestheSqlDataSourcesDelete() Method

Step2:AutomaticallyGeneratingtheINSERT,UPDATE,andDELETE
Statements
AsStep1examined,INSERT,UPDATE,andDELETE SQLstatementscanbespecifiedthroughthePropertieswindow
orthecontrolsdeclarativesyntax.However,thisapproachrequiresthatwemanuallywriteouttheSQLstatements
byhand,whichcanbemonotonousanderrorprone.Fortunately,theConfigureDataSourcewizardprovidesan
optiontohavetheINSERT,UPDATE,andDELETE statementsautomaticallygeneratedwhenusingtheSpecify

6 of12

columnsfromatableofviewscreen.
Letsexplorethisautomaticgenerationoption.AddaDetailsViewtotheDesignerinInsertUpdateDelete.aspx
andsetitsID propertytoManageProducts.Next,fromtheDetailsViewssmarttag,choosetocreateanewdata
sourceandcreateaSqlDataSourcenamedManageProductsDataSource.

Figure6:CreateaNewSqlDataSourceNamedManageProductsDataSource
FromtheConfigureDataSourcewizard,opttousetheNORTHWINDConnectionString connectionstringandclick
Next.Fromthe ConfiguretheSelectStatementscreen,leavetheSpecifycolumnsfromatableorviewradio
buttonselectedandpicktheProducts tablefromthedropdownlist.SelecttheProductID,ProductName,
UnitPrice,andDiscontinued columnsfromthecheckboxlist.

7 of12

Figure7:UsingtheProducts Table,ReturntheProductID,ProductName,UnitPrice,andDiscontinued
Columns
ToautomaticallygenerateINSERT,UPDATE,andDELETE statementsbasedontheselectedtableandcolumns,click
theAdvancedbuttonandchecktheGenerateINSERT,UPDATE,andDELETE statementscheckbox.

Figure8:ChecktheGenerateINSERT,UPDATE,andDELETE statements Checkbox


TheGenerateINSERT,UPDATE,andDELETE statements checkboxwillonlybecheckableifthetableselectedhas
aprimarykeyandtheprimarykeycolumn(orcolumns)areincludedinthelistofreturnedcolumns.TheUse
optimisticconcurrencycheckbox,whichbecomesselectableoncetheGenerateINSERT,UPDATE,andDELETE
statements checkboxhasbeenchecked,willaugmenttheWHERE clausesintheresultingUPDATE andDELETE
8 of12

statementstoprovideoptimisticconcurrencycontrol.Fornow,leavethischeckboxuncheckedwellexamine
optimisticconcurrencywiththeSqlDataSourcecontrolinthenexttutorial.
AftercheckingtheGenerateINSERT,UPDATE,andDELETE statementscheckbox,clickOKtoreturntothe
ConfigureSelectStatement screen,thenclickNext,andthenFinish,tocompletetheConfigureDataSource
wizard.Uponcompletingthewizard,VisualStudiowilladdBoundFieldstotheDetailsViewfortheProductID,
ProductName,andUnitPrice columnsandaCheckBoxFieldfortheDiscontinued column.Fromthe
DetailsViewssmarttag,checktheEnablePagingoptionsothattheuservisitingthispagecanstepthroughthe
products.AlsoclearouttheDetailsViewsWidth andHeight properties.
NoticethatthesmarttaghastheEnableInserting, EnableEditing, andEnableDeleting optionsavailable.
ThisisbecausetheSqlDataSourcecontainsvaluesforitsInsertCommand,UpdateCommand,andDeleteCommand,
asthefollowingdeclarativesyntaxshows:
<asp:DetailsViewID="ManageProducts"runat="server"AllowPaging="True"
AutoGenerateRows="False"DataKeyNames="ProductID"
DataSourceID="ManageProductsDataSource"EnableViewState="False">
<Fields>
<asp:BoundFieldDataField="ProductID"HeaderText="ProductID"
InsertVisible="False"ReadOnly="True"SortExpression="ProductID"/>
<asp:BoundFieldDataField="ProductName"HeaderText="ProductName"
SortExpression="ProductName"/>
<asp:BoundFieldDataField="UnitPrice"HeaderText="UnitPrice"
SortExpression="UnitPrice"/>
<asp:CheckBoxFieldDataField="Discontinued"HeaderText="Discontinued"
SortExpression="Discontinued"/>
</Fields>
</asp:DetailsView>
<asp:SqlDataSourceID="ManageProductsDataSource"runat="server"
ConnectionString="<%$ConnectionStrings:NORTHWNDConnectionString%>"
DeleteCommand=
"DELETEFROM[Products]WHERE[ProductID]=@ProductID"
InsertCommand=
"INSERTINTO[Products]([ProductName],[UnitPrice],[Discontinued])
VALUES(@ProductName,@UnitPrice,@Discontinued)"
SelectCommand=
"SELECT[ProductID],[ProductName],[UnitPrice],[Discontinued]
FROM[Products]"
UpdateCommand=
"UPDATE[Products]SET[ProductName]=@ProductName,
[UnitPrice]=@UnitPrice,[Discontinued]=@Discontinued
WHERE[ProductID]=@ProductID">
<DeleteParameters>
<asp:ParameterName="ProductID"Type="Int32"/>
</DeleteParameters>
<UpdateParameters>
<asp:ParameterName="ProductName"Type="String"/>
<asp:ParameterName="UnitPrice"Type="Decimal"/>
<asp:ParameterName="Discontinued"Type="Boolean"/>
<asp:ParameterName="ProductID"Type="Int32"/>
</UpdateParameters>
<InsertParameters>
<asp:ParameterName="ProductName"Type="String"/>
<asp:ParameterName="UnitPrice"Type="Decimal"/>
<asp:ParameterName="Discontinued"Type="Boolean"/>
</InsertParameters>
</asp:SqlDataSource>

NotehowtheSqlDataSourcecontrolhashadvaluesautomaticallysetforitsInsertCommand,UpdateCommand,and

9 of12

DeleteCommand properties.ThesetofcolumnsreferencedintheInsertCommand and UpdateCommand properties


arebasedonthoseintheSELECT statement.Thatis,ratherthanhavingeveryProductscolumninthe
InsertCommand andUpdateCommand,thereareonlythosecolumnsspecifiedinthe SelectCommand (less
ProductID,whichisomittedbecauseitsanIDENTITY column,whosevaluecannotbechangedwheneditedand
whichisautomaticallyassignedwheninserting).Moreover,foreachparameterintheInsertCommand,
UpdateCommand,andDeleteCommand propertiestherearecorrespondingparametersintheInsertParameters,
UpdateParameters,andDeleteParameters collections.

ToturnontheDetailsViewsdatamodificationfeatures,checkthe EnableInserting, EnableEditing, and


EnableDeletingoptionsinitssmarttag.ThisaddsaCommandFieldwithits ShowInsertButton,
ShowEditButton,andShowDeleteButton propertiessettoTrue.
VisitthepageinabrowserandnotetheEdit,Delete,andNewbuttonsincludedintheDetailsView.Clickingthe
EditbuttonturnstheDetailsViewintoeditmode,whichdisplayseachBoundFieldwhoseReadOnly propertyisset
toFalse (thedefault)asaTextBox,andtheCheckBoxFieldasacheckbox.

Figure9:TheDetailsViewsDefaultEditingInterface
Similarly,youcandeletethecurrentlyselectedproductoraddanewproducttothesystem.Sincethe
InsertCommand statementonlyworkswiththeProductName,UnitPrice,andDiscontinued columns,theother
columnshaveeitherNULL ortheirdefaultvalueassignedbythedatabaseuponinsert.Justlikewiththe
ObjectDataSource,iftheInsertCommand ismissinganydatabasetablecolumnsthatdontallowNULLsanddont
haveadefaultvalue,aSQLerrorwilloccurwhenattemptingtoexecutetheINSERT statement.
Note: TheDetailsViewsinsertingandeditinginterfaceslackanysortofcustomizationorvalidation.Toadd
validationcontrolsortocustomizetheinterfaces,youneedtoconverttheBoundFieldstoTemplateFields.Referto
theAddingValidationControlstotheEditingandInsertingInterfacesandCustomizingtheDataModification
Interface tutorialsformoreinformation.
Also,keepinmindthatforupdatinganddeleting,theDetailsViewusesthecurrentproductsDataKey value,
whichisonlypresentiftheDataKeyNames propertyisconfigured.Ifeditingordeletingappearstohavenoeffect,
ensurethattheDataKeyNames propertyisset.

10 of12

LimitationsofAutomaticallyGeneratingSQLStatements
SincetheGenerateINSERT,UPDATE,andDELETE statements optionisonlyavailablewhenpickingcolumnsfrom
atable,formorecomplexqueriesyouwillhavetowriteyourownINSERT,UPDATE,andDELETE statementslikewe
didinStep1.Commonly,SQLSELECT statementsuseJOINstobringbackdatafromoneormorelookuptablesfor
displaypurposes(suchasbringingbacktheCategories tablesCategoryName fieldwhendisplayingproduct
information).Atthesametime,wemightwanttoallowtheusertoedit,update,orinsertdataintothecoretable
(Products,inthiscase).
WhiletheINSERT,UPDATE,andDELETE statementscanbeenteredmanually,considerthefollowingtimesaving
tip.InitiallysetuptheSqlDataSourcesothatitpullsbackdatajustfromtheProducts table.UsetheConfigure
DataSourcewizardsSpecifycolumnsfromatableorviewscreensothatyoucanautomaticallygeneratethe
INSERT,UPDATE,andDELETE statements.Then,aftercompletingthewizard,choosetoconfiguretheSelectQuery
fromthePropertieswindow(or,alternatively,gobacktotheConfigureDataSourcewizard,butusethe Specifya
customSQLstatementorstoredprocedure option).ThenupdatetheSELECT statementtoincludetheJOIN syntax.
ThistechniqueoffersthetimesavingbenefitsoftheautomaticallygeneratedSQLstatementsandallowsfora
morecustomizedSELECT statement.
AnotherlimitationofautomaticallygeneratingtheINSERT,UPDATE,andDELETE statementsisthatthecolumnsin
theINSERT andUPDATE statementsarebasedonthecolumnsreturnedbytheSELECT statement.Wemayneedto
updateorinsertmoreorfewerfields,however.Forexample,intheexamplefromStep2,maybewewanttohave
theUnitPrice BoundFieldbereadonly.Inthatcase,itshouldntappearintheUpdateCommand.Orwemaywant
tosetthevalueofatablefieldthatdoesnotappearintheGridView.Forexample,whenaddinganewrecordwe
maywanttheQuantityPerUnit valuesettoTODO.
Ifsuchcustomizationsarerequired,youneedtomakethemmanually,eitherthroughthePropertieswindow,the
SpecifyacustomSQLstatementorstoredprocedure optioninthewizard,orviathedeclarativesyntax.
Note:WhenaddingparametersthatdonothavecorrespondingfieldsinthedataWebcontrol,keepinmindthat
theseparametersvalueswillneedtobeassignedvaluesinsomemanner.Thesevaluescanbe:hardcodeddirectly
intheInsertCommand orUpdateCommandcancomefromsomepredefinedsource(thequerystring,sessionstate,
Webcontrolsonthepage,andsoon)orcanbeassignedprogrammatically,aswesawintheprecedingtutorial.

Summary
InorderforthedataWebcontrolstoutilizetheirbuiltininserting,editing,anddeletingcapabilities,thedata
sourcecontroltheyareboundtomustoffersuchfunctionality.FortheSqlDataSource,thismeansthatINSERT,
UPDATE,andDELETE SQLstatementsmustbeassignedtotheInsertCommand,UpdateCommand,and
DeleteCommand properties.Theseproperties,andthecorrespondingparameterscollections,canbeaddedmanually
orgeneratedautomaticallythroughtheConfigureDataSourcewizard.Inthistutorialweexaminedboth
techniques.
WeexaminedusingoptimisticconcurrencywiththeObjectDataSourceintheImplementingOptimistic
Concurrency tutorial.TheSqlDataSourcecontrolalsoprovidesoptimisticconcurrencysupport.AsnotedinStep2,
whenautomaticallygeneratingtheINSERT,UPDATE,andDELETE statements,thewizardoffersaUseoptimistic
concurrency option.Aswellseeinthenexttutorial,usingoptimisticconcurrencywiththeSqlDataSource
modifiestheWHERE clausesintheUPDATE andDELETE statementstoensurethatthevaluesfortheothercolumns
haventchangedsincethedatawaslastdisplayedonthepage.
HappyProgramming!

11 of12

AbouttheAuthor
ScottMitchell,authorofsevenASP/ASP.NETbooksandfounderof4GuysFromRolla.com,hasbeenworkingwith
MicrosoftWebtechnologiessince1998.Scottworksasanindependentconsultant,trainer,andwriter.Hislatest
bookisSamsTeachYourselfASP.NET2.0in24Hours.Hecanbereachedatmitchell@4GuysFromRolla.com. or
viahisblog,whichcanbefoundat http://ScottOnWriting.NET.

12 of12

You might also like