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 ?
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
I am not sure about the reason but it also happened to me but at that time I was in a bit hurry, so I opted an alternate way. When I get datatable from ViewState, I made a new table and loop through records of original table and set values in new table :) so my viewstate table remained untouched.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With