Adding or Modifying Your Records: Updating Data

In this lesson, you will learn how to create a data-entry form to update data in the local database.

In the last three lessons, you created a database, added a database file to your project, and created a basic user interface. As you may have noticed, you could change the address data and even add new records—but if you closed the program and started it again, those changes were lost.

This data was actually a copy of the data in the database, stored in a local DataSet. Each time the program starts, the DataSet retrieves its data from the database. When changes are made in the DataSet they are not made in the database.

If you click the Save button on the AddressesBindingNavigator control, any changes are copied from the DataSet back to the database. Since a user probably will not always remember to save their work, add code to automatically save changes to the database when the program closes. While you are at it, you will also change the user interface to make data entry easier.

Try It!

To update the local database file

  1. Open the Addresses project from the previous lesson. If you have not yet completed the previous lesson, go to Showing Information to the User: Displaying Data in Your User Interface and complete the steps.

  2. In Solution Explorer, select the database and ensure that the Copy to Output Directory property value is set to Copy if newer.

  3. In Solution Explorer, select Form1, and then, on the View menu, click Designer.

  4. On the form, select the AddressesDatGridView control and delete it.

  5. In Solution Explorer, click the Data Sources tab.

  6. In the Data Sources window, select the Addresses table, and then click Details in the drop-down list.

  7. Drag the Addresses node from the Data Sources window to the new form.

    TextBox controls are added for each field in the table, together with Label controls that describe the fields.

  8. Double-click the form to open the Code Editor.

  9. In the Events drop-down list, click FormClosing.

  10. In the Form1_FormClosing event handler, type the following code:

    Me.AddressesBindingSource.EndEdit()
    Me.AddressesTableAdapter.Update(Me.FirstDatabaseDataSet.Addresses)
    

    This code causes the AddressesTableAdapter to copy any changes in the dataset back to the local database.

  11. Press F5 to run your program.

    Make changes to some of the data, or add a new record, and then close the form.

  12. Press F5 again. Your changes should be saved.

In this lesson, you learned how to update a database. In the next lesson, you will learn how to connect to a sample database and display related data on a form.

Next Lesson: Displaying Related Data

See Also

Tasks

Getting the Information You Need: Connecting to an Existing Database

Other Resources

Managing Your Records: Using Data in Your Program

Visual Basic Guided Tour

SQL Server Compact 3.5 Books Online