Manual data binding using WriteValue

I have had similar requirements for a form. In my case I only wanted the databinding for all the form's controls to occur when I clicked the form's Save button.

The best solution I found was to set each binding's DataSourceUpdateMode to OnValidation then set the containing form's AutoValidate property to Disable. This prevents binding as you change focus between controls on the form. Then in the Click event for my Save button, I manually validate my form's input and, if it is OK, call the form's ValidateChildren method to trigger the binding.

This method also has the advantage of giving you full control over how you validate your input. WinForms do not include a good way to do this by default.


I believe I recently read on stackoverflow where this was given as an answer: Disable Two Way Databinding

public static class DataBindingUtils
{
    public static void SuspendTwoWayBinding( BindingManagerBase bindingManager )
    {
        if( bindingManager == null )
        {
           throw new ArgumentNullException ("bindingManager");
        }

        foreach( Binding b in bindingManager.Bindings )
        {
            b.DataSourceUpdateMode = DataSourceUpdateMode.Never;
        }
    }

    public static void UpdateDataBoundObject( BindingManagerBase bindingManager )
    {
        if( bindingManager == null )
        {
           throw new ArgumentNullException ("bindingManager");
        }

        foreach( Binding b in bindingManager.Bindings )
        {
            b.WriteValue ();
        }
    }
}