Search code examples
c#winformsbindingieditableobject

Prevent IEditableObject.BeginEdit() is called multiple times


I have an entity, e.g. customer inherited from IEditableObject, like described here:

public class Customer : IEditableObject
{
    ...
    private Boolean backupAvailable = false;
    private ThisObject backupData;

    public void BeginEdit()
    {
        if (!backupAvailable)
        {
            this.backupData.Name = this.Name;
            backupAvailable = true;
        }
    }

    public void CancelEdit()
    {
        if (backupAvailable)
        {
            this.Name = this.backupData.Name;
            backupAvailable = false;
        }
    }

    public void EndEdit()
    {
        if (backupAvailable)
        {
            backupData = new ThisObject();
            backupAvailable = false;
        }
    }
}

In my UI class I have a BindingSource, where all controls are bind to, and 2 buttons "Change" and "Cancel":

BindingSource BSCustomer;

private void buttonChange_Click(object sender, EventArgs e)
{
    ...
    ((Customer)BSCustomer.Current).BeginEdit();
}


private void buttonCancel_Click(object sender, EventArgs e)
{
    ...
    ((Customer)BSCustomer.Current).CancelEdit();
}

This works fine.

But now I've detected, that BeginEdit() is not only called from my explicit call, but called from many other code, e.g.:

BSCustomer.AllowNew = true;

or

BSCustomer.AddNew();

or

BSCustomer.IndexOf();

When I click now the button "Change", backupAvailable is already set with wrong values. When I click "Cancel" the wrong values are wrote back.

Are there any possibilities to prevent this callings? Or can I differ in BeginEdit() where the call comes from?


Solution

  • Just removing :IEditableObject is the solution. Without that, BeginEdit() is just called when it's called manually.

    All the credits to Ivan.