Saving a DataView in Session

Most .NET developers store a DataSet in a Session variable, then create a DataView from the DataSet's DataTable on Page_Load in order to get a different sort and/or filter. 

However, you can store the DataView in a Session variable by itself! And it will still contain data when you pull it out of the Session variable on another page!

' Create and fill a DataTable from Northwind's Customer table
Dim connString As String
= "Server=(local);Database=Northwind;UID=sa;PWD=myPassword"
Dim sqlConn As SqlClient.SqlConnection = New
SqlClient.SqlConnection(connString)
Dim sqlSelectCmd As SqlClient.SqlCommand = New
SqlClient.SqlCommand("Select * From Customers", sqlConn)
Dim sqlDataAdapter As SqlClient.SqlDataAdapter = New
SqlClient.SqlDataAdapter
sqlDataAdapter.SelectCommand = sqlSelectCmd
Dim dataTable As DataTable = New DataTable("Customers")
sqlDataAdapter.Fill(dataTable)

' Create a new DataView from the Customers DataTable
Dim dataView As DataView = dataTable.DefaultView

' Place the DataView into Session var
Session("dataView") = dataView

' Redirect to another web page
Response.Redirect("WebForm2.aspx") 
 

Now you might think (as I did for a while) that the DataView is making a copy of the DataTable into it's Table property (since rows.count was > 0).

Dim dataView As DataView = DirectCast(Session("dataView"), DataView)
Dim rowCount As Integer = dataView.Table.Rows.Count
 

However, that is not the case (thanks to Thomas Tomiczek who noticed the correct behavior)!  What happens is that the DataView still has a reference to the DataTable.  And hence that DataTable stays in memory until the DataView releases the reference. Then the DataTable will be removed when GC occurs.

Saving a DataView in session is pretty cool (most folks don't know that you can do this). But the key point here is that the DataView does NOT make a copy of the data. It still is using the referenced DataTable underneath the covers... 

 

5 Comments

Comments have been disabled for this content.