1 out of 3 rated this helpful - Rate this topic

Walkthrough: Saving Data to a Database (Multiple Tables)

Updated: May 2011

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 items from the Data Sources window, code to save data is automatically added for the first table dropped onto a form. Any additional tables added to a form require the manual addition of any code required to save data. This walkthrough shows how to add code to save updates from more than one table.

NoteNote

Your computer might show different names or locations for some of the Visual Studio user interface elements in the following instructions. The Visual Studio edition that you have and the settings that you use determine these elements. For more information, see Visual Studio Settings.

Tasks illustrated in this walkthrough include:

In order to complete this walkthrough, you will need:

The first step is to create a Windows Application. Assigning a name to the project is optional at this step but we will give it a name because we are planning on saving it later.

To create the new Windows Application project

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

  2. Name the project UpdateMultipleTablesWalkthrough.

  3. Select Windows Application and click OK. For more information, see Creating Windows-Based Applications.

    The UpdateMultipleTablesWalkthrough project is created and added to Solution Explorer.

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. For information on setting up the Northwind sample database, see How to: Install Sample Databases.

To create the data source

  1. On the Data menu, click Show Data Sources.

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

  3. Select Database on the Choose a Data Source Type page, and then click Next.

  4. On the Choose your Data Connection page 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. For more information, see Add/Modify Connection Dialog Box (General).

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

  6. Click Next on the Save connection string to the Application Configuration file page.

  7. Expand the Tables node on the Choose your Database Objects page.

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

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

For this walkthrough the data in the Customers table will be in a Details layout where data is displayed in individual controls. The data from the Orders table will be in a Grid layout displayed in a DataGridView control.

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

  1. Expand the Customers node in the Data Sources window.

  2. Change the control of the Customers table to individual controls by selecting Details from the control list on the Customers node. For more information, see How to: Set the Control to be Created when Dragging from the Data Sources Window.

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.

    NoteNote

    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.

You can update the database by calling the Update methods of the Customers and Orders TableAdapters. By default, an event handler for the BindingNavigator's Save button is added to the form's code to send updates to the database. This procedure modifies that code to send updates in the proper order to eliminate 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.

NoteNote

For clarity this walkthrough does not use a transaction, but if you are updating two or more related tables, then you should include all the update logic within a transaction. A transaction is a process that assures all related changes to a database are successful before committing any changes. For more information, see Transactions and Concurrency (ADO.NET).

To add update logic to the application

  1. Double-click the Save button on the BindingNavigator to open 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 (Deleted, Added, and Modified). Then updates are executed in the proper 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();
        }
    }
    
    
    

To test the application

  1. Press F5.

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

  3. Press the Save button.

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

    NoteNote

    For example code that demonstrates how to update the list of Orders when you change Customers or add new Customer and Orders data, see How to: Insert New Records into a Database and Walkthrough: Saving Data from Related Data Tables (Hierarchical Update).

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

Date

History

Reason

May 2011

Added links to additional sample code.

Customer feedback.

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.