Jaa


Update data by using a TableAdapter

Applies to: yesVisual Studio noVisual Studio for Mac

Note

This article applies to Visual Studio 2017. If you're looking for the latest Visual Studio documentation, see Visual Studio documentation. We recommend upgrading to the latest version of Visual Studio. Download it here

After the data in your dataset has been modified and validated, you can send the updated data back to a database by calling the Update method of a TableAdapter. The Update method updates a single data table and runs 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 use to do the updates. The TableAdapterManager class ensures that updates are made in the correct order based on the foreign-key constraints that are defined in the database. When you use data-bound controls, the databinding architecture creates a member variable of the TableAdapterManager class called tableAdapterManager.

Note

When you try to update a data source with the contents of a dataset, you can get errors. To avoid errors, we recommend that you put the code that calls the adapter's Update method inside a try/catch block.

The exact procedure for updating a data source can vary depending on business needs, but includes 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.

  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 try the update again (HasErrors, GetErrors).

Save data to a database

Call the Update method of a TableAdapter. Pass 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 TableAdapter'sUpdate method in a try/catch block. The following example shows how to update the contents of the Customers table in NorthwindDataSet from within a try/catch block .

    try
    {
        this.Validate();
        this.customersBindingSource.EndEdit();
        this.customersTableAdapter.Update(this.northwindDataSet.Customers);
        MessageBox.Show("Update successful");
    }
    catch (System.Exception ex)
    {
        MessageBox.Show("Update failed");
    }
    
    Try
        Me.Validate()
        Me.CustomersBindingSource.EndEdit()
        Me.CustomersTableAdapter.Update(Me.NorthwindDataSet.Customers)
        MsgBox("Update successful")
    
    Catch ex As Exception
        MsgBox("Update failed")
    End Try
    

See also