当我更新Gridview中的行时,我得到“对象引用未设置为对象的实例”。经过数小时的研究,我无法弄清楚。
这个小项目是使用Cache来处理断开连接的数据访问。
以下是代码:
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”];
答案 0 :(得分:0)
我会尝试在数据绑定时填充数据键,然后在RowUpdating方法中读取它们以获取当前ID。因此,在gvStudents.DataBind();
之后,添加
gvStudents.DataKeyNames = new string[] { "ID" };
然后,在RowUpdating方法中,从数据键中获取当前ID:
var currentID = gvStudents.DataKeys[e.RowIndex].Value;