6.5. Using a Transaction with a DataAdapter
Problem
You need to use a transaction when
updating
a data source using a DataAdapter.
Solution
Associate a Transaction with
the
appropriate Command object from
the DataAdapter.
The sample code contains three event handlers:
Form.LoadSets up the sample by using a
DataAdapterto load aDataTablewith the Orders table from the Northwind database. ACommandBuilderis used to generate the updating logic. The default view of theDataTableis bound to a data grid on the form.- Update
Button.Click Creates a new
Transactionobject on theConnectionof theSelectCommandof theDataAdapter. TheTransactionis associated with theConnectionobjects for the update commands generated for theDataAdapterby theCommandBuilder. TheUpdate( )method of theDataAdapteris called to updateDataTablechanges to the Orders table. If no errors are encountered, the transaction is committed; otherwise, all changes made are rolled back.- Refresh
Button.Click Clears and reloads the Orders
DataTable.
The C# code is shown in Example 6-7.
Example 6-7. File: TransactionDataAdapter.cs
// Namespaces, variables, and constants using System; using System.Configuration; using System.Windows.Forms; using System.Data; using System.Data.SqlClient; private const String ORDERS_TABLE = "Orders"; private DataTable dt; private SqlDataAdapter da; private SqlCommandBuilder cb; // . . . private void TransactionDataAdapterForm_Load(object sender, System.EventArgs e) { String sqlText = "SELECT ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access