.net 如何在会话中存储DataTable并检索它

tvokkenx  于 2023-10-21  发布在  .NET
关注(0)|答案(5)|浏览(146)

如何在C#/.NET中将数据表存储在Session中并从Session中检索值?

9gm1akwq

9gm1akwq1#

将数据表添加到会话中:

DataTable Tissues = new DataTable();

Tissues = dal.returnTissues("TestID", "TestValue");// returnTissues("","") sample     function for adding values

Session.Add("Tissues", Tissues);

从会话中检索数据表:

DataTable Tissues = Session["Tissues"] as DataTable

DataTable Tissues = (DataTable)Session["Tissues"];
ru9i0ody

ru9i0ody2#

要在会话中存储DataTable,请执行以下操作:

DataTable dtTest = new DataTable();
Session["dtTest"] = dtTest;

要从会话中检索DataTable,请执行以下操作:

DataTable dt = (DataTable) Session["dtTest"];
gcmastyq

gcmastyq3#

您可以这样做,但在Session中存储数据集对象不是很有效。如果你有一个有很多用户的Web应用程序,它会很快阻塞你的服务器内存。
如果您真的必须这样做,我建议您在不需要数据集时立即将其从会话中删除。

0g0grzrc

0g0grzrc4#

一般来说,你要做的是保持Session和ViewState的大小较小。我通常只在Session和ViewState中存储ID和少量数据包。
例如,如果你想将大量数据从一个页面传递到另一个页面,你可以在查询字符串中存储一个ID,并使用该ID从数据库或文件中获取数据。

7xzttuei

7xzttuei5#

// 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);
    }
}

相关问题