Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Build Your Own ASP.NET 2.0 Web Site Using CSharp And VB (2006) [eng]-1.pdf
Скачиваний:
142
Добавлен:
16.08.2013
Размер:
15.69 Mб
Скачать

Updating a Database from a Modified DataSet

The DataView class has a property named RowFilter that allows you to specify an expression similar to that of an SQL statement’s WHERE clause. For instance, the following filter selects all departments whose names start with “a”:

Visual Basic

dataTable.DefaultView.RowFilter = "Department LIKE 'a%'"

C#

dataTable.DefaultView.RowFilter = "Department LIKE 'a%'";

Updating a Database from a Modified

DataSet

So far, we’ve used the DataSet exclusively for retrieving and binding database data to controls such as the GridView. The reverse operation—updating data within a database from a DataSet—is also possible using the Update method of the SqlDataAdapter.

The SqlDataAdapter has the following four properties, which represent the main database commands:

SelectCommand

InsertCommand

UpdateCommand

DeleteCommand

The SelectCommand contains the command that’s executed when we call Fill. The other properties are quite similar, except that you must call the Update method instead.

If we want to insert, update, or remove records in a database, we simply make modifications to the data in the DataSet or DataTable, then call the Update method of the SqlDataAdapter. This will automatically execute the SQL queries specified in the InsertCommand, UpdateCommand, and DeleteCommand properties as appropriate.

The excellent news is that ADO.NET also provides an object named

SqlCommandBuilder, which creates the UPDATE, DELETE, and INSERT code for us.

521

Chapter 12: Advanced Data Access

Basically, we just need to populate the DataSet or DataTable objects (usually by performing a SELECT query), then use SqlDataAdapter and SqlCommandBuilder to do the rest of the work for us.

In the example below, we’ll see a modified version of BindGrid that adds a new department, called New Department, to the database. The new lines are highlighted (note that I’ve simplified BindGrid by removing the code that stores and retrieves the DataSet from view state, as well as the code that sorts the results):

Visual Basic

Private Sub BindGrid() ' Define data objects

Dim conn As SqlConnection Dim dataSet As New DataSet

Dim adapter As SqlDataAdapter

Dim dataRow As DataRow

Dim commandBuilder As SqlCommandBuilder

'Read the connection string from Web.config Dim connectionString As String = _

ConfigurationManager.ConnectionStrings( _ "Dorknozzle").ConnectionString

'Initialize connection

conn = New SqlConnection(connectionString) ' Create adapter

adapter = New SqlDataAdapter( _

"SELECT DepartmentID, Department FROM Departments", _ conn)

'Fill the DataSet adapter.Fill(dataSet, "Departments")

'Make changes to the table

dataRow = dataSet.Tables("Departments").NewRow() dataRow("Department") = "New Department" dataSet.Tables("Departments").Rows.Add(dataRow) ' Submit the changes

commandBuilder = New SqlCommandBuilder(adapter) adapter.Update(dataSet.Tables("Departments"))

' Bind the grid to the DataSet departmentsGrid.DataSource = _

dataSet.Tables("Departments").DefaultView departmentsGrid.DataBind()

End Sub

C#

private void BindGrid()

{

// Define data objects

522

Updating a Database from a Modified DataSet

SqlConnection conn;

DataSet dataSet = new DataSet();

SqlDataAdapter adapter;

DataRow dataRow ;

SqlCommandBuilder commandBuilder;

//Read the connection string from Web.config string connectionString =

ConfigurationManager.ConnectionStrings[

"Dorknozzle"].ConnectionString;

//Initialize connection

conn = new SqlConnection(connectionString); // Create adapter

adapter = new SqlDataAdapter(

"SELECT DepartmentID, Department FROM Departments", conn);

//Fill the DataSet adapter.Fill(dataSet, "Departments");

//Make changes to the table

dataRow = dataSet.Tables["Departments"].NewRow(); dataRow["Department"] = "New Department"; dataSet.Tables["Departments"].Rows.Add(dataRow); // Submit the changes

commandBuilder = new SqlCommandBuilder(adapter); adapter.Update(dataSet.Tables["Departments"]); departmentsGrid.DataSource = dataSet.Tables["Departments"]; departmentsGrid.DataBind();

}

If you run this code a few times, you’ll have lots of “New Department” departments added to the database, as shown in Figure 12.27.

As you can see, adding a new record is a trivial task. The work that’s required to submit the changes to the database requires us to write just two rows of code. The rest of the new code creates the new row that was inserted.

We create an SqlCommandBuilder object, passing in our SqlDataAdapter. The SqlCommandBuilder class is responsible for detecting modifications to the DataSet and deciding what needs to be inserted, updated, or deleted to apply those changes to the database. Having done this, SqlCommandBuilder generates the necessary SQL queries and stores them in the SqlDataAdapter for the Update method to use. It should be no surprise, then, that our next action is to call the Update method of the SqlDataAdapter object, passing in the DataTable that needs updating.

523

Chapter 12: Advanced Data Access

Figure 12.27. Adding many new departments

Deleting all of these new departments is also an easy task. The following code browses the Departments DataTable and deletes all departments with the name

New Department:

Visual Basic

' Define data objects

Dim conn As SqlConnection Dim dataSet As New DataSet

Dim adapter As SqlDataAdapter

Dim commandBuilder As SqlCommandBuilder

'Read the connection string from Web.config Dim connectionString As String = _

ConfigurationManager.ConnectionStrings( _ "Dorknozzle").ConnectionString

'Initialize connection

conn = New SqlConnection(connectionString) ' Create adapter

adapter = New SqlDataAdapter( _

"SELECT DepartmentID, Department FROM Departments", _ conn)

' Fill the DataSet

524

Updating a Database from a Modified DataSet

adapter.Fill(dataSet, "Departments")

' Make changes to the table

For Each dataRow As DataRow In dataSet.Tables("Departments").Rows If dataRow("Department") = "New Department" Then

dataRow.Delete() End If

Next

' Submit the changes

commandBuilder = New SqlCommandBuilder(adapter) adapter.Update(dataSet.Tables("Departments"))

' Bind the grid to the DataSet departmentsGrid.DataSource = _

dataSet.Tables("Departments").DefaultView departmentsGrid.DataBind()

Note that in the C# version the conversion to string needs to be performed explicitly:

C#

//Define data objects SqlConnection conn;

DataSet dataSet = new DataSet(); SqlDataAdapter adapter; SqlCommandBuilder commandBuilder;

//Read the connection string from Web.config string connectionString =

ConfigurationManager.ConnectionStrings[

"Dorknozzle"].ConnectionString;

//Initialize connection

conn = new SqlConnection(connectionString); // Create adapter

adapter = new SqlDataAdapter(

"SELECT DepartmentID, Department FROM Departments", conn);

//Fill the DataSet adapter.Fill(dataSet, "Departments");

//Make changes to the table

foreach (DataRow dataRow in dataSet.Tables["Departments"].Rows)

{

if(dataRow["Department"].ToString() == "New Department")

{

dataRow.Delete();

}

}

// Submit the changes

commandBuilder = new SqlCommandBuilder(adapter); adapter.Update(dataSet.Tables["Departments"]);

525