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


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.

System_CAPS_ICON_note.jpg 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.

  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)

  2. Add the following line of code immediately before any calls to save the form's data (the TableAdapterManager.UpdateAll() method):


Bind Windows Forms controls to data in Visual Studio
Hierarchical update