简体   繁体   中英

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 ?

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.

像这样使用它解决了引用问题

DataTable dt2= ( (DataTable)ViewState["dtThis"]).Copy(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM