Reputation: 1989
This is a C# Windows Forms project. I have a grid on a form. To get the data for the grid, I run a SQL procedure and store the results in a class. I want to have a copy of that class so I know what the values were before the user changes them in the grid. So I assign the class to another class. Then I assign the first class as the grid's datasource. However, after the change is made, both the original class and the copy have the same values. How do I prevent this?
Here's is my code:
List<Unreceive> receivedItems = new List<Unreceive>();
List<Unreceive> listItems = mpBLL.GetMPItemsReceived();
receivedItems = listItems;
gcUnreceive.DataSource = listItems;
at this point, let's say receivedItems.quantity and listItems.quantity have a value of 100.
The user changes the data in the grid so the quantity is 50. That triggers this code:
private void gvUnreceive_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
{
DevExpress.XtraGrid.Views.Grid.GridView gridView = (DevExpress.XtraGrid.Views.Grid.GridView) sender;
int index = gridView.GetDataSourceRowIndex(rowHandle);
Unreceive selectedItem = listItems[index];
Unreceive originalItem = receivedItems[index];
int newQuantity = selectedItem.quantity;
int originalQuantity = originalItem.quantity;
}
At this point I want: newQuantity = 50; originalQuantity = 100;
But what I get is: newQuantity = 50; original Quantity = 50;
It's like I passed a variable by reference instead of by value, but I haven't passed it anywhere. How do I fix this so that the receivedItems class isn't effected by what happens to the listItems class or the datagrid?
Upvotes: -1
Views: 102
Reputation: 1
Yes you are right that it seems "byRef"
receivedItems = listItems; "object = object" would share the Pointer to where the data is not create a new pointer to a new data structure.
You were on the right track in creating a new list initially. List receivedItems = new List();
You need to loop through your original list and create new distinct list items for the copy list - setting each property to the value of the master list. This will give you two lists with separate memory storage.
Upvotes: 0