Save data to a database (multiple tables)

Note

This article applies to Visual Studio 2015. 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

One of the most common scenarios in application development is to display data on a form in a Windows application, edit the data, and send the updated data back to the database. This walkthrough creates a form that displays data from two related tables and shows how to edit records and save changes back to the database. This example uses the Customers and Orders tables from the Northwind sample database.

You can save data in your application back to the database by calling the Update method of a TableAdapter. When you drag tables from the Data Sources window onto a form, the code that's required to save data is automatically added.Any additional tables that are added to a form require the manual addition of this code. This walkthrough shows how to add code to save updates from more than one table.

Note

The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings or the edition that you're using. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see Customizing Development Settings in Visual Studio.

Tasks illustrated in this walkthrough include:

Prerequisites

In order to complete this walkthrough, you will need:

  • Access to the Northwind sample database.

Create the Windows application

The first step is to create a Windows Application. Assigning a name to the project is optional during this step, but we'll give it a name because we're planning on saving it later.

To create the new Windows application project

  1. On the File menu, create a new project.

  2. Name the project UpdateMultipleTablesWalkthrough.

  3. Select Windows Application, and then select OK. For more information, see Client Applications.

    The UpdateMultipleTablesWalkthrough project is created and added to Solution Explorer.

Create the data source

This step creates a data source from the Northwind database using the Data Source Configuration Wizard. You must have access to the Northwind sample database to create the connection.

To create the data source

  1. On the Data menu, selectShow Data Sources.

  2. In the Data Sources window, selectAdd New Data Source to start the Data Source Configuration Wizard.

  3. On the Choose a Data Source Typescreen, select Database, and then select Next.

  4. On the Choose your Data Connectionscreen do one of the following:

    • If a data connection to the Northwind sample database is available in the drop-down list, select it.

      -or-

    • Select New Connection to open the Add/Modify Connection dialog box.

  5. If your database requires a password, select the option to include sensitive data, and then select Next.

  6. On the Save connection string to the Application Configuration file, select Next.

  7. On the Choose your Database Objectsscreen, expand the Tables node .

  8. Select the Customers and Orders tables, and then select Finish.

    The NorthwindDataSet is added to your project, and the tables appear in the Data Sources window.

Set the controls to be created

For this walkthrough, the data in the Customers table is in a Details layout where data is displayed in individual controls. The data from the Orders table is in a Grid layout that's displayed in a DataGridView control.

To set the drop type for the items in the Data Sources window

  1. In the Data Sources window, expand the Customers node.

  2. On the Customers node, select Details from the control list to change the control of the Customers table to individual controls. For more information, see Set the control to be created when dragging from the Data Sources window.

Create the data-bound form

You can create the data-bound controls by dragging items from the Data Sources window onto your form.

To create data-bound controls on the form

  1. Drag the main Customers node from the Data Sources window onto Form1.

    Data-bound controls with descriptive labels appear on the form, along with a tool strip (BindingNavigator) for navigating records. A NorthwindDataSet, CustomersTableAdapter, BindingSource, and BindingNavigator appear in the component tray.

  2. Drag the related Orders node from the Data Sources window onto Form1.

    Note

    The related Orders node is located below the Fax column and is a child node of the Customers node.

    A DataGridView control and a tool strip (BindingNavigator) for navigating records appear on the form. An OrdersTableAdapter and BindingSource appear in the component tray.

Addcode to update the database

You can update the database by calling the Update methods of the Customers and Orders TableAdapters. By default, an event handler for the Save button of theBindingNavigator is added to the form's code to send updates to the database. This procedure modifies the code to send updates in the correct order.This eliminates the possibility of raising referential integrity errors. The code also implements error handling by wrapping the update call in a try-catch block. You can modify the code to suit the needs of your application.

Note

For clarity, this walkthrough does not use a transaction.However, if you're updating two or more related tables, include all the update logic within a transaction. A transaction is a process that assures that all related changes to a database are successful before any changes are committed. For more information, see Transactions and Concurrency.

To add update logic to the application

  1. Select the Save button on the BindingNavigator.This opens the Code Editor to the bindingNavigatorSaveItem_Click event handler.

  2. Replace the code in the event handler to call the Update methods of the related TableAdapters. The following code first creates three temporary data tables to hold the updated information for each DataRowState (DataRowState, DataRowState, and DataRowState). Then updates are run in the correct order. The code should look like the following:

    this.Validate();
    this.ordersBindingSource.EndEdit();
    this.customersBindingSource.EndEdit();
    
    NorthwindDataSet.OrdersDataTable deletedOrders = (NorthwindDataSet.OrdersDataTable)
        northwindDataSet.Orders.GetChanges(DataRowState.Deleted);
    
    NorthwindDataSet.OrdersDataTable newOrders = (NorthwindDataSet.OrdersDataTable)
        northwindDataSet.Orders.GetChanges(DataRowState.Added);
    
    NorthwindDataSet.OrdersDataTable modifiedOrders = (NorthwindDataSet.OrdersDataTable)
        northwindDataSet.Orders.GetChanges(DataRowState.Modified);
    
    try
    {
        // Remove all deleted orders from the Orders table.
        if (deletedOrders != null)
        {
            ordersTableAdapter.Update(deletedOrders);
        }
    
        // Update the Customers table.
        customersTableAdapter.Update(northwindDataSet.Customers);
    
        // Add new orders to the Orders table.
        if (newOrders != null)
        {
            ordersTableAdapter.Update(newOrders);
        }
    
        // Update all modified Orders.
        if (modifiedOrders != null)
        {
            ordersTableAdapter.Update(modifiedOrders);
        }
    
        northwindDataSet.AcceptChanges();
    }
    
    catch (System.Exception ex)
    {
        MessageBox.Show("Update failed");
    }
    
    finally
    {
        if (deletedOrders != null)
        {
            deletedOrders.Dispose();
        }
        if (newOrders != null)
        {
            newOrders.Dispose();
        }
        if (modifiedOrders != null)
        {
            modifiedOrders.Dispose();
        }
    }
    
    Me.Validate()
    Me.OrdersBindingSource.EndEdit()
    Me.CustomersBindingSource.EndEdit()
    
    Dim deletedOrders As NorthwindDataSet.OrdersDataTable = CType(
        NorthwindDataSet.Orders.GetChanges(Data.DataRowState.Deleted), NorthwindDataSet.OrdersDataTable)
    
    Dim newOrders As NorthwindDataSet.OrdersDataTable = CType(
        NorthwindDataSet.Orders.GetChanges(Data.DataRowState.Added), NorthwindDataSet.OrdersDataTable)
    
    Dim modifiedOrders As NorthwindDataSet.OrdersDataTable = CType(
        NorthwindDataSet.Orders.GetChanges(Data.DataRowState.Modified), NorthwindDataSet.OrdersDataTable)
    
    
    Try
        ' Remove all deleted orders from the Orders table.
        If Not deletedOrders Is Nothing Then
            OrdersTableAdapter.Update(deletedOrders)
        End If
    
        ' Update the Customers table.
        CustomersTableAdapter.Update(NorthwindDataSet.Customers)
    
        ' Add new orders to the Orders table.
        If Not newOrders Is Nothing Then
            OrdersTableAdapter.Update(newOrders)
        End If
    
        ' Update all modified Orders.
        If Not modifiedOrders Is Nothing Then
            OrdersTableAdapter.Update(modifiedOrders)
        End If
    
        NorthwindDataSet.AcceptChanges()
    
    Catch ex As Exception
        MsgBox("Update failed")
    
    Finally
        If Not deletedOrders Is Nothing Then
            deletedOrders.Dispose()
        End If
    
        If Not newOrders Is Nothing Then
            newOrders.Dispose()
        End If
    
        If Not modifiedOrders Is Nothing Then
            modifiedOrders.Dispose()
        End If
    End Try
    

Test the application

To test the application

  1. Select F5.

  2. Make some changes to the data of one or more records in each table.

  3. Select the Save button.

  4. Check the values in the database to verify that the changes were saved.

Next Steps

Depending on your application requirements, there are several steps you might want to perform after creating a data-bound form in your Windows application. Some enhancements you could make to this walkthrough include:

See Also

Save data back to the database