从数据表中删除的行也从创建数据表会话变量中删除 [英] Rows removed from a datatable are also removed from the session variable that created the datatable
问题描述
我与会话变量中存储的数据表时注意到一些奇怪的行为。从一个从会话变量创建一个DataTable中删除一行似乎也修改会话变量如下证明。
I am noticing some strange behavior when working with datatables stored in session variables. Removing a row from a datatable that is created from a session variable appears to also modify the session variable as demonstrated below.
<asp:GridView ID="gvResults" runat="server" DataKeyNames="id">
<Columns>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:Button ID="btnSelectUserToRemove" runat="server" CausesValidation="false" CommandName="Remove" Text="Select" CommandArgument='<%# Eval("id") %>' OnCommand="Command" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
public partial class Test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dtResults = new DataTable();
dtResults.Columns.Add("id");
dtResults.Rows.Add();
dtResults.Rows[0]["id"] = "1";
dtResults.Rows.Add();
dtResults.Rows[1]["id"] = "2";
Session["id"] = dtResults;
gvResults.DataSource = dtResults;
gvResults.DataBind();
}
}
protected void Command(object sender, CommandEventArgs e)
{
if (e.CommandName == "Remove")
{
DataTable dtTemp = (DataTable)Session["id"];
for (Int32 i = 0; i < dtTemp.Rows.Count; i++)
{
if (e.CommandArgument.ToString() == dtTemp.Rows[i]["id"].ToString())
{
dtTemp.Rows[i].Delete(); //Should just remove the row from the datatable.
}
}
dtTemp.AcceptChanges();
}
DisplayData();
}
protected void DisplayData()
{
gvResults.DataSource = (DataTable)Session["id"];
gvResults.DataBind(); //Should display both rows because I did not save the modified datatable back to this session variable.
}
}
我不保存修改 dtTemp
数据表回会话[身份证]
变量。这是我的理解是应该有 dtTemp
1的行,因为一个行已被删除,而在 2行会话[身份证]
打电话时 DisplayData code>。但是,只有一个行后显示在GridView
DisplayData code>运行。
I am not saving the modified dtTemp
datatable back to the Session["id"]
variable. It is my understanding that there should be 1 row in dtTemp
, because one row was deleted, and 2 rows in Session["id"]
when calling DisplayData
. However, only one row is displayed in the gridview after DisplayData
runs.
我希望有一个人在那里,可以解释为什么这种情况正在发生的一些情况。
I am hoping there is someone out there that can shed some light on why this is happening.
推荐答案
这是因为 dtTemp
和会话变量是对象引用都指向同一个对象。
It's because dtTemp
and the session variable are object references that both point to the same object.
这篇关于从数据表中删除的行也从创建数据表会话变量中删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!