How to: Update Data by Using a TableAdapter

How to: Update Data by Using a TableAdapter

 

After the data in your dataset has been modified and validated, you can send the updated data back to a databaseby calling the Update method of a TableAdapter. The Update method will update a single data table and execute the correct command (INSERT, UPDATE, or DELETE) based on the RowState of each data row in the table. When a dataset has related tables, Visual Studio generates a TableAdapterManager class that you should use to do the updates. The TableAdapterManager ensures that updates are made the correct order based on the foreign-key constraints defined in the database. When you use data-bound controls, the databinding architecture creates a member variable of the TableAdapterManager for you,called tableAdapterManager. For more information, see Hierarchical Update Overview.

System_CAPS_noteNote

Because trying to update a data source with the contents of a dataset can cause errors, you should put the code that calls the adapter's Update method inside a try/catch block.

The exact procedure to update a data source can vary depending on business needs, but your application should include the following steps:

  1. Call the adapter's Update method in a try/catch block.

  2. If an exception is caught, locate the data row that caused the error. For more information, see How to: Locate Rows that Have Errors.

  3. Reconcile the problem in the data row (programmatically if you can, or by presenting the invalid row to the user for modification), and then reattempt the update (HasErrors, GetErrors).

Call the Update method of a TableAdapter, passing the name of the data table that contains the values to be written to the database.

To update a database by using a TableAdapter

  • Enclose the adapter's Update method in a try/catch block. The following example shows how to attempt an update from within a try/catch block with the contents of the Customers table in NorthwindDataSet.

    try
    {
        this.Validate();
        this.customersBindingSource.EndEdit();
        this.customersTableAdapter.Update(this.northwindDataSet.Customers);
        MessageBox.Show("Update successful");
    }
    catch (System.Exception ex)
    {
        MessageBox.Show("Update failed");
    }
    
Show:
© 2016 Microsoft