Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ViewState updates automatically while updating DataTable

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 ?

like image 819
nirav Avatar asked Jan 26 '26 10:01

nirav


2 Answers

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

like image 134
rt2800 Avatar answered Jan 29 '26 00:01

rt2800


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.

like image 23
Imran Balouch Avatar answered Jan 28 '26 22:01

Imran Balouch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!