Updating with SQL and ADO.NET

There are two aspects to writing web applications that allow users to update data. The first aspect is providing the user with a form that facilitates data modification. The second is to provide the programmatic support for the update: how do you insert new records, or modify or delete existing records once you know what changes you want to make, if you use the ADO.NET object model directly?

Updating data in a database is simple if you update a single table, but once you update related tables, things get complicated. You can use transactions to ensure the integrity of your data, as shown below.

The simplest way to update the database using ADO.NET objects directly is to generate a SQL Insert, Update, or Delete statement, and execute it using the Command object’s ExecuteNonQuery method. To see this at work, create a new web site called UpdatingDBDirectly. Drag a GridView to display the Shipper’s table and add a Select button to the first column of the grid.

Below the grid, add three buttons and two text boxes. Name the buttons btnAdd, btnEdit and btnDelete, and name the text boxes txtName and txtPhone, as shown in Figure 10-14.

Updating DB Directly user interface

Figure 10-14. Updating DB Directly user interface

The content file to create this is shown in Example 10-9.

Example 10-9. default.aspx for UpdatingDBDirectly

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" ...

Get Programming ASP.NET, 3rd Edition 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.