Commit in-process edits on data-bound controls before saving data

Note

Datasets and related classes are legacy .NET Framework technologies from the early 2000s that enable applications to work with data in memory while the applications are disconnected from the database. They are especially useful for applications that enable users to modify data and persist the changes back to the database. Although datasets have proven to be a very successful technology, we recommend that new .NET applications use Entity Framework Core. Entity Framework provides a more natural way to work with tabular data as object models, and it has a simpler programming interface.

When editing values in data-bound controls, users must navigate off the current record to commit the updated value to the underlying data source that the control is bound to. When you drag items from the Data Sources Window onto a form, the first item that you drop generates code into the Save button click event of the BindingNavigator. This code calls the EndEdit method of the BindingSource. Therefore, the call to the EndEdit method is generated only for the first BindingSource that is added to the form.

The EndEdit call commits any changes that are in process, in any data-bound controls that are currently being edited. Therefore, if a data-bound control still has focus and you click the Save button, all pending edits in that control are committed before the actual save (the TableAdapterManager.UpdateAll method).

You can configure your application to automatically commit changes, even if a user tries to save data without committing the changes, as part of the save process.

Note

The designer adds the BindingSource.EndEdit code only for the first item dropped onto a form. Therefore, you have to add a line of code to call the EndEdit method for each BindingSource on the form. You can manually add a line of code to call the EndEdit method for each BindingSource. Alternatively, you can add the EndEditOnAllBindingSources method to the form and call it before you perform a save.

The following code uses a LINQ (Language Integrated Query) query to iterate all BindingSource components and call the EndEdit method for each BindingSource on a form.

To call EndEdit for all BindingSource components on a form

  1. Add the following code to the form that contains the BindingSource components.

    private void EndEditOnAllBindingSources()
    {
        var BindingSourcesQuery =
            from Component bindingSources in this.components.Components
            where bindingSources is BindingSource
            select bindingSources;
    
        foreach (BindingSource bindingSource in BindingSourcesQuery)
        {
            bindingSource.EndEdit();
        }
    }
    
  2. Add the following line of code immediately before any calls to save the form's data (the TableAdapterManager.UpdateAll() method):

    EndEditOnAllBindingSources();