Persisting object changes from child form to parent form based on button press.
- by Shyran
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;
}
}