Raj
Raj

Reputation: 22926

How to save a copy of a object and restore it later

I have a form which has a ListView and buttons to add/edit/delete items from this list. It has a save & a cancel button. On pressing the cancel button, I want to revert all the changes that have been done in the current form. So, while loading the form I keep a copy of the original list like below.

backupMyListView = MyListView

In the cancel button code, I do the opposite.

MyListView = refMyListView

Whats happening is that, the original listview is never restored because everytime MyListView was updated, backupMyListView also was getting updated.

How do I restore the original ListView on pressing the cancel button?

Upvotes: 1

Views: 209

Answers (3)

Writwick
Writwick

Reputation: 2163

Like This :

Private List<ListViewItem> ListViewStore As New List<ListViewItem>;
Sub Backup()
    For Each ListViewItem LItem in MyListView.Items
        ListViewStore.Add(LItem.Clone)
    Next
End Sub

Upvotes: 1

Steven Doggart
Steven Doggart

Reputation: 43743

You need to look into the difference between Value Types and Reference Types. When you set a variable to the value of another variable, it only copies the data if the value is a Value Type of object (a TypeDef structure). When the value is a Reference Type of object (a Class), it just makes another reference to the same object. So if you create a new ListView object (a reference type) and set two different variables to it, they will both point to the same object. Any changes made through one variable will also affect the other variable. To make a copy of the data, you need to use the Clone method.

Upvotes: 1

LarsTech
LarsTech

Reputation: 81610

Both lists are obviously referencing the same list.

You basically need to clone or copy the objects:

Dim backupMyListView As New ListView
For Each lv As ListViewItem In MyListView.Items
  backupMyListView.Items.Add(lv.Clone)
Next

Upvotes: 2

Related Questions