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
?
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.