04-10-2012, 11:45 AM
Working with Data in ASP.NET 2.0 Inserting, Updating, and Deleting Data with the SqlDataSource
Working with Data.pdf (Size: 616.55 KB / Downloads: 130)
Introduction
As discussed in An Overview of Inserting, Updating, and Deleting, the GridView control provides builtin
updating and deleting capabilities, while the DetailsView and FormView controls include inserting support along
with editing and deleting functionality. These data modification capabilities can be plugged directly into a data
source control without a line of code needing to be written. An Overview of Inserting, Updating, and Deleting
examined using the ObjectDataSource to facilitate inserting, updating, and deleting with the GridView,
DetailsView, and FormView controls. Alternatively, the SqlDataSource can be used in place of the
ObjectDataSource.
Recall that to support inserting, updating, and deleting, with the ObjectDataSource we needed to specify the object
layer methods to invoke to perform the insert, update, or delete action. With the SqlDataSource, we need to provide
INSERT, UPDATE, and DELETE SQL statements (or stored procedures) to execute. As we’ll see in this tutorial, these
statements can be created manually or can be automatically generated by the SqlDataSource’s Configure Data
Source wizard.
Configuring the GridView for Deleting
With the DeleteCommand property added, the GridView’s smart tag now contains the “Enable Deleting” option. Go
ahead and check this checkbox. As discussed in An Overview of Inserting, Updating, and Deleting, this causes the
GridView to add a CommandField with its ShowDeleteButton property set to true. As Figure 4 shows, when the
page is visited through a browser a Delete button is included. Test this page out by deleting some products.
Upon clicking a Delete button, a postback occurs, the GridView assigns the ProductID parameter the value of the
DataKeys collection value for the row whose Delete button was clicked, and invokes the SqlDataSource’s Delete
() method. The SqlDataSource control then connects to the database and executes the DELETE statement. The
GridView then rebinds to the SqlDataSource, getting back and displaying the current set of products (which no
longer includes the justdeleted
record).
Note: Since the GridView uses its DataKeys collection to populate the SqlDataSource parameters, it’s vital that the
GridView’s DataKeyNames property be set to the column(s) that constitute the primary key and that the
SqlDataSource’s SelectCommand returns these columns. Moreover, it’s important that the parameter name in the
SqlDataSource’s DeleteCommand is set to @ProductID. If the DataKeyNames property is not set or the parameter is
not named @ProductsID, clicking the Delete button will cause a postback, but won’t actually delete any record.