ViewState updates automatically while updating DataTable

asp.net, c#, datatable, viewstate

Solution

You are storing reference of datatable into viewstate. So what ever updates done on `viewstate["dtThis"]` is directly affecting original Datatable obj assigned in `method1()`.

One way to preserve original view state datatable is to use DataTable.Copy() to create replica of original and operate on that replica

Problem

I am assigning a DataTable in a ViewState. ``` public void Method1() { DataTable dt = getData(); //Gets the Data ViewState["dtThis"] = dt; } ``` Now when 'Method2' executes ViewState will be assigned to DataTable. ``` public void Method2() { DataTable dt2 = (DataTable)ViewState["dtThis"]; dt2.Columns.Remove("FirstName"); //Removing a column dt2.AcceptChanges(); } ``` Now after the execution of the Method2 when I check (DataTable)ViewState("dtThis") its having DataTable dt2 even if I didn't assign dt2 back to ViewState("dtThis"). (means the column - "FirstName" is removed in the ViewSate("dtThis") DataTable). Any idea why this type of behaviour of the ViewState? And how to maintain the original ViewState ?

Original source