Question

I'm having some troubles using Session Variables as they are being used as Reference and I want to use them as value.

I got to this debuging my solution and I created something like:

DataTable dt = 
     (DataTable)HttpContext.Current.Session[
                      "SearchReturn-DataTableSchema"];

// Adding Rows of Data to DataTable dt

HttpContext.Current.Session["SearchReturn-DataTable"] = dt;

((DataTable)HttpContext.Current.Session[
     "SearchReturn-DataTableSchema"]).Rows.Clear();

return dt;

my idea was to have in "DataTableSchema" only the DataTable with the Columns Schema and in "DataTable" the Columns + Rows.

Problem is that when I clear all rows from DataTableSchema, the variable dt will have the Rows cleared as well (!!)

How can avoid this? How can assign a variable (in this case a Session variable) as a value and not as a reference?

Thank you.


Answer

this

DataTable dt = (DataTable)Session["SearchReturn-DataTableSchema"];

needs to be this:

DataTable dt = ((DataTable)Session["SearchReturn-DataTableSchema"]).Copy();

:-)

Was it helpful?

Solution

You'll have to make a copy of your table.

OTHER TIPS

An interesting part of this is that the behaviour will depend on your session-state provider. You are presumably using the in-process provider at the moment, which keeps references - but most providers (understandably) use serialization.

This often bites people when they try to scale up, as they find that they have something non-serializable in session. So you might consider pushing state into a different provider; SQL-Server, memcached, etc - they will all do serialization so the data will be independent.

Also You can Clone DataTable Schema using Clone method. And then Load data via Load and CreateReader methods.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top