vrijdag 19 juni 2009

WinForms: DataBinding on a cancellable Dialog Form

On some occasions, you might want to create a dialog window that enables a user to modify data.

In almost all situations, you will want to make use of the databinding capabilities in the .NET Framework, so that you do not have to write the tedious synchronization-code yourself.

However, when you want to databind a custom object to the controls on the dialog-form, databinding might get in the way:
When you change the Text in a TextBox that is databound on a property of your object, the property of your object will be updated as soon as the databound TextBox has been validated (default behaviour).
This is not a problem, until the user decides that he does not want to keep the changes he has made, and clicks the Cancel button of the dialog form.
In such a case, you want to revert back to the original state of the object.

There are several solutions to handle this problem.

One solution is to implement some kind of Undo-behaviour in your custom object, but this might be a little bit overkill for the situation at hand.

A more simple solution, is to disable the 2-way databinding when the form is displayed, and explicitly update the databound object when the user clicks the Ok button of the dialog.

This can be done like this:

public class MyEditForm : Form
{
public MyEditForm( MyClass objectToDisplay )
{
// Suppose that you have defined databindings via the
// designer
this.MyBindingSource.DataSource = objectToDisplay;

DataBindingUtils.SuspendTwoWayBinding(this.BindingContext[MyBindingSource]);
}

public void btnOk_Click( object sender, EventArgs e )
{
DataBindingUtils.UpdateDataBoundObject(this.BindingContext[MyBindingSource]);
this.DialogResult = DialogResult.Ok;
}

public void btnCancel_Click( object sender, EventArgs e )
{
this.DialogResult = DialogResult.Cancel;
}
}

The concept is very simple; when the form is displayed, we suspend the databindings, so that changes that are made to the controls on the form, are not directly persisted in the underlying object.
When the user confirms the changes he has made by clicking the OK-button, we need to make sure that the contents of the controls are persisted in the underlying object.

The two methods that are of interest look like this:

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 ();
}
}
}