Reputation: 4137
How can I store a datatable in a Session and retrieve the values from the Session in C#/.NET?
Upvotes: 14
Views: 127191
Reputation: 4886
Generally what you want to do is keep size on the Session and ViewState small. I generally just store IDs and small amounts of packets in Session and ViewState.
For instance if you want to pass large chunks of data from one page to another, you can store an ID in the querystring and use that ID to either get data from a database or a file.
Upvotes: 1
Reputation: 363
// DECLARATION
HttpContext context = HttpContext.Current;
DataTable dt_ShoppingBasket = context.Session["Shopping_Basket"] as DataTable;
// TRY TO ADD rows with the info into the DataTable
try
{
// Add new Serial Code into DataTable dt_ShoppingBasket
dt_ShoppingBasket.Rows.Add(new_SerialCode.ToString());
// Assigns new DataTable to Session["Shopping_Basket"]
context.Session["Shopping_Basket"] = dt_ShoppingBasket;
}
catch (Exception)
{
// IF FAIL (EMPTY OR DOESN'T EXIST) -
// Create new Instance,
DataTable dt_ShoppingBasket= new DataTable();
// Add column and Row with the info
dt_ShoppingBasket.Columns.Add("Serial");
dt_ShoppingBasket.Rows.Add(new_SerialCode.ToString());
// Assigns new DataTable to Session["Shopping_Basket"]
context.Session["Shopping_Basket"] = dt_PanierCommande;
}
// PRINT TESTS
DataTable dt_To_Print = context.Session["Shopping_Basket"] as DataTable;
foreach (DataRow row in dt_To_Print.Rows)
{
foreach (var item in row.ItemArray)
{
Debug.WriteLine("DATATABLE IN SESSION: " + item);
}
}
Upvotes: 0
Reputation: 29
To store DataTable
in Session:
DataTable dtTest = new DataTable();
Session["dtTest"] = dtTest;
To retrieve DataTable
from Session:
DataTable dt = (DataTable) Session["dtTest"];
Upvotes: 2
Reputation: 2218
Add a datatable into session:
DataTable Tissues = new DataTable();
Tissues = dal.returnTissues("TestID", "TestValue");// returnTissues("","") sample function for adding values
Session.Add("Tissues", Tissues);
Retrive that datatable from session:
DataTable Tissues = Session["Tissues"] as DataTable
or
DataTable Tissues = (DataTable)Session["Tissues"];
Upvotes: 32
Reputation: 653
You can do it like that but storing a DataSet object in Session is not very efficient. If you have a web app with lots of users it will clog your server memory really fast.
If you really must do it like that I suggest removing it from the session as soon as you don't need the DataSet.
Upvotes: 1