![](/img/trans.png)
[英]Get DataField value while updating row (asp GridView) asp.NET C#
[英]Getting error when updating a Gridview row in ASP.NET C#
更新Gridview中的行時,出現“對象引用未設置為對象實例”的信息。 經過數小時的研究,我無法弄清楚。
這個小項目用於使用緩存來處理斷開的數據訪問。
這是代碼:
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”];
我將在數據綁定時嘗試填充數據鍵,然后在RowUpdating方法中從它們讀取以獲取當前ID。 因此,在gvStudents.DataBind();
之后gvStudents.DataBind();
,添加
gvStudents.DataKeyNames = new string[] { "ID" };
然后,在您的RowUpdating方法中,從數據鍵獲取當前ID:
var currentID = gvStudents.DataKeys[e.RowIndex].Value;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.