views:

65

answers:

4

Hi,

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();

:-)

+3  A: 

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

No Refunds No Returns
forgot all about DataTable.Copy() :)
balexandre
A: 

Use the .Copy() Method of your DataTable:
http://msdn.microsoft.com/en-us/library/system.data.datatable.copy.aspx

dbemerlin
+2  A: 

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.

Marc Gravell
The good about knowing what and how .NET handles stuff :) BTW: Are you "always" online? Don't you sleep? Work? ;-)
balexandre
If you look closely at my usage, you'll see *very* clearly-defined gaps during work time (except maybe for lunch)... let's just say we "had words" about it ;-p But sleep is over-rated...
Marc Gravell
A: 

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

Sergey Mirvoda