Deleting Data

Example 7-7 shows how you can use the DataSet and SqlDataAdapter classes to delete data from the Titles table. This example shows the implementation of an ASP.NET page that displays data from the Titles table and allows users to delete a row from the table by clicking a button.

Warning

Unless you don’t care about the state of the Pubs sample database, it would probably be a good idea to back up the database before deleting any of the rows in the Titles table (just in case you want to restore the database to its original state later).

As with the previous example, we use a DataGrid control to display the items in the dataset. However, in this case, we set the AutoGenerateColumns property of the DataGrid to False and supply BoundColumn controls for each displayed column. This provides greater flexibility in displaying the data, including the ability to determine which columns are displayed, the header to use for each column, and in the case of the price data, the ability to specify a format string for the data. This example also adds an <alternatingitemstyle> tag to specify that every other row should have a background color of silver. To enable handling of the Delete button, we set the DataGrid’s onDeleteCommand method to the name of the event handler for the Delete button.

As with the previous example, Example 7-7 declares both the DataSet and SqlDataAdapter instances at the page level to make them available to all procedures; in the Page_Load event handler, we call ...

Get ASP.NET in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.