tags:

views:

23

answers:

1

I have created a form that is used for both adding and editing a custom object. Which mode the form takes is provided by an enum value passed from the calling code. I also pass in an object of the custom type. All of my controls at data bound to the specific properties of the custom object. When the form is in Add mode, this works great as when the controls are updated with data, the underlying object is as well. However, in Edit mode, I keep two variables of the custom object supplied by the calling code, the original, and a temporary one made through deep copying. The controls are then bound to the temporary copy, this makes it easy to discard the changes if the user clicks the Cancel button. What I want to know is how to persist those changes back to the original object if the user clicks the OK button, since there is now a disconnect because of the deep copying. I am trying to avoid implementing a internal property on the Add/Edit form if I can. Below is an example of my code:


public AddEditCustomerDialog(Customer customer, DialogMode mode)
{
   InitializeComponent();
   InitializeCustomer(customer, mode);
}
private void InitializeCustomer(Customer customer, DialogMode mode)
{
   this.customer = customer;
   if (mode == DialogMode.Edit)
   {
      this.Text = "Edit Customer";
      this.tempCustomer = ObjectCopyHelper.DeepCopy(this.customer);
      this.customerListBindingSource.DataSource = this.tempCustomer;
      this.phoneListBindingSource.DataSource = this.tempCustomer.PhoneList;
   }
   else
   {
      this.customerListBindingSource.DataSource = this.customer;
      this.phoneListBindingSource.DataSource = this.customer.PhoneList;
   }
}
A: 

You could always add a function to your object (Customer), either as "Copy(Customer cust)" or "Update(Customer cust)" and consume the changes that way.

The other way would be to have a wrapper class around Customer EditableCustomer, which takes a customer object in its constructor EditableCustomer(Customer root) and uses that to hold the changes. In the final event just call a function like "UpdateRoot()" and populate the changes back to the original customer, failing to call this will be the same as a discard.

You wont be able to use deep copies directly but this will allow you to control this type of situation, and actually allow you to control both edits and undo's dynamically.

GrayWizardx
I like the idea of the wrapper class if I could make it generic. Customer is one of many custom classes I'd like to be able to change in this manner and I want to avoid having to implement a copy method for each one, and a base class/interface is out of the question as each class is only related by being properties of another class.
Shyran
In the interests of time, it looks like I will have to go with the Copy(object) implementation. Thanks for your response.
Shyran