0

I'm using ObjectListView and the object I'm adding to it is a custom Class that I've built for it.

My Class contains information for doing calculations. I want to allow users to be able to edit calculations they've already made.

I've tried pulling the object from the ObjectListView with the following different code:

Customer customer = (Customer)listCustomers.SelectedItem.RowObject;

Customer customer = (Customer)listCustomers.GetSelectedObject();

Customer customer = (Customer)listCustomers.SelectedObject;

All of those methods result in the customer to become that object. The problem I'm facing though, is if I change any of the values of that class, such as the following code, it reflects the change in that object in the ObjectListView:

customer.TotalValue += 50;

And even if I run those calculations on another form, by transferring that information via:

EditCustomer editForm = new EditCustomer(customer)
editForm.Show();

It still changes the object in the ObjectListView.

What I'm wondering, is how can I extract that object, and allow me to edit the customer object, while not changing the object in the ObjectListView?

Jack Nelson
  • 83
  • 1
  • 6
  • See the notes on the [IClonable](https://learn.microsoft.com/en-us/dotnet/api/system.icloneable) Interface and the [MemberwiseClone](https://learn.microsoft.com/en-us/dotnet/api/system.object.memberwiseclone) Method – Jimi Jan 02 '20 at 02:33

1 Answers1

1

Your customer variable is a reference to the object stored in your ObjectListView, so when you modify customer, the change is reflected in the underlying object it is referencing. When you pass customer to a different form, you are passing the reference, still pointing to the same underlying object, so that object can then be modified through that reference, even from a different form.

To get the behavior you want, you need to clone your object, making a completely separate copy of it, and then making changes to the copy will not impact the original.

Check here for information on cloning objects.

Paul
  • 597
  • 2
  • 5
  • I appreciate the answer you gave Paul. It pointed me on the right path, and I realized I don't need to do a deep clone, but actually I was able to do a shallow clone with the following code: `public Customer ShallowCopy() { return (Customer)this.MemberwiseClone(); }` I appreciate you sending me on the right path. Just wish I would have known this before I spent the last 3 hours trying to figure this out on my own! – Jack Nelson Jan 02 '20 at 02:52