C# 在ASP.NET C中更新Gridview行时出错#
当我更新Gridview中的一行时,得到的是“对象引用未设置为对象的实例”。经过数小时的研究,我无法理解 这个小项目用于使用缓存处理断开连接的数据访问 代码如下:C# 在ASP.NET C中更新Gridview行时出错#,c#,asp.net,C#,Asp.net,当我更新Gridview中的一行时,得到的是“对象引用未设置为对象的实例”。经过数小时的研究,我无法理解 这个小项目用于使用缓存处理断开连接的数据访问 代码如下: private void GetDataFromDB() { string CS = ConfigurationManager.ConnectionStrings["TST"].ConnectionString; SqlConnection conn = new SqlConnection(C
private void GetDataFromDB()
{
string CS = ConfigurationManager.ConnectionStrings["TST"].ConnectionString;
SqlConnection conn = new SqlConnection(CS);
string strSelectQry = "Select * From tblStudents";
SqlDataAdapter da = new SqlDataAdapter(strSelectQry, conn);
DataSet ds = new DataSet();
da.Fill(ds, "Students"); // fill dataset with records from select query and name table "Students" (can name whatever you like).
ds.Tables["Students"].PrimaryKey = new DataColumn[] {ds.Tables["Students"].Columns["ID"] };
Cache.Insert("DATASET", ds, null, DateTime.Now.AddHours(24), System.Web.Caching.Cache.NoSlidingExpiration);
gvStudents.DataSource = ds;
gvStudents.DataBind();
}
protected void gvStudents_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
if (Cache["DATASET"] != null)
{
DataSet ds = (DataSet)Cache["DATASET"];
DataRow dr = ds.Tables["Students"].Rows.Find(e.Keys["ID"]); // get the row thats being edited
dr["Name"] = e.NewValues["Name"]; // update fields in datarow
dr["Gender"] = e.NewValues["Gender"];
dr["TotalMarks"] = e.NewValues["TotalMarks"];
// store the dataset back into the cache
Cache.Insert("DATASET", ds, null, DateTime.Now.AddHours(24), System.Web.Caching.Cache.NoSlidingExpiration);
gvStudents.EditIndex = -1; // take row out of edit mode
GetDataFromCache(); // update gridview with updated dataset from cache
}
}
我在“gvStudents_RowUpdating(…)”方法的行中得到了对象引用错误:dr[“Name”]=e.NewValues[“Name”] 我会尝试在数据绑定时填充数据键,然后在行更新方法中读取它们以获取当前ID代码>,添加
gvStudents.DataKeyNames = new string[] { "ID" };
然后,在RowUpdate方法中,从数据键获取当前ID:
var currentID = gvStudents.DataKeys[e.RowIndex].Value;
你试过调试应用程序并检查什么是空的(dr应该是空的)?@Gusman是的,我调试过,dr是空的。但是dr应该包含正在编辑的Gridview行中的数据。如果要通过ID在缓存中搜索dr,请检查是否已收到ID,以及缓存是否真的工作。@Gusman我检查了e.键,但没有数据。值是空的…我不明白为什么。我还检查了“ds”,它显示的计数为7,表中有7行,但我无法查看ds中的行。这样做只会给我该行的ID。我需要以DataRow的形式访问正在更新或更改的整行,以便进行更新。正确,您仍然需要此行:
DataRow dr=ds.Tables[“Students”].Rows.Find(e.Keys[“ID”])代码>只需将e.Keys[“ID”]
替换为gvStudents.DataKeys[e.RowIndex].Value
。