Csharp/C#教程:ASP .NET RowUpdating GridView令人烦恼分享


ASP .NET RowUpdating GridView令人烦恼

我在使用RowUpdating方法时遇到问题。 我的GridView连接到我们的本地SQL Server,我正在尝试更新数据。 以下是MSDN中RowUpdating方法的代码。

 protected void TaskGridView_RowUpdating(object sender, GridViewUpdateEventArgs e) { //Retrieve the table from the session object. DataTable dt = (DataTable)Session["TaskTable"]; //Update the values. GridViewRow row = GridView1.Rows[e.RowIndex]; dt.Rows[row.DataItemIndex]["Id"] = ((TextBox)(row.Cells[1].Controls[0])).Text; dt.Rows[row.DataItemIndex]["Description"] = ((TextBox)(row.Cells[2].Controls[0])).Text; dt.Rows[row.DataItemIndex]["IsComplete"] = ((CheckBox)(row.Cells[3].Controls[0])).Checked; //Reset the edit index. GridView1.EditIndex = -1; //Bind data to the GridView control. BindData(); } 

我收到此错误:

System.NullReferenceException:未将对象引用设置为对象的实例。

试试这段代码一次。

 protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) { GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex]; int id = Int32.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString()); TextBox tname = (TextBox)row.FindControl("nam"); TextBox tques = (TextBox)row.FindControl("que"); MySqlCommand cmd = new MySqlCommand("update exam set name1=@name,ques=@ques where id = @id", con); cmd.Parameters.Add("@id", MySqlDbType.Int16).Value = id; cmd.Parameters.Add("@name", MySqlDbType.VarChar, 30).Value = tname.Text.Trim(); cmd.Parameters.Add("@ques", MySqlDbType.VarChar,40).Value = tques.Text.Trim(); con.Open(); cmd.ExecuteNonQuery(); GridView1.EditIndex = -1; bind(); } 

并非所有GridViewRow都有DataItem。

您应该在代码周围添加if块,并validation正在更新的行是DataRow类型。

 if (e.Row.RowType == DataControlRowType.DataRow) { your code here... } 

有关RowTypes的更多信息: http : //msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridviewrow.rowtype.aspx

上述就是C#学习教程:ASP .NET RowUpdating GridView令人烦恼分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

 public void bindGvEdit() { GridView1.DataSource = obj1.SelectAlltbl(); GridView1.DataBind(); } protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) { GridView1.EditIndex = e.NewEditIndex; bindGvEdit(); } protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { GridView1.EditIndex = -1; bindGvEdit(); } protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) { GridViewRow row = GridView1.Rows[e.RowIndex]; obj1.Id = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value); obj1.Name = ((TextBox)row.Cells[1].Controls[1]).Text; obj1.Description = ((TextBox)row.Cells[2].Controls[1]).Text; obj1.Updatetbl(); GridView1.EditIndex = -1; bindGvEdit(); } 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1006811.html

(0)
上一篇 2021年12月29日
下一篇 2021年12月29日

精彩推荐