C# 更新gridview时出错?

C# 更新gridview时出错?,c#,asp.net,.net,gridview,nullreferenceexception,C#,Asp.net,.net,Gridview,Nullreferenceexception,更新gridview上的值时,我收到以下错误消息: “对象引用未设置为对象的实例” 我的c代码是: 您需要更新代码,以检查从gridview分配的控件是否为空。还要做一些异常处理 protected void gvDetails_RowUpdating(object sender, GridViewUpdateEventArgs e) { try { int nmbr = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToS

更新gridview上的值时,我收到以下错误消息:

“对象引用未设置为对象的实例”

我的c代码是:


您需要更新代码,以检查从gridview分配的控件是否为空。还要做一些异常处理

protected void gvDetails_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
  try
  {
  int nmbr = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());
  TextBox name = (TextBox)GridView1.Rows[e.RowIndex].FindControl("names");
  TextBox dept = (TextBox)GridView1.Rows[e.RowIndex].FindControl("depts");
  TextBox quantity = (TextBox)GridView1.Rows[e.RowIndex].FindControl("quantitys");
  //do check that any of your controls here is not null
  if(name!=null && dept!=null && quantity !=null)
  {
      con.Open();
      SqlCommand cmds=new SqlCommand("update erbp set name ='" + name.Text + "',dept ='"+ 
          dept.Text+"',quantity='" + quantity.Text + "' where inmbr=" + nmbr , con);
      cmds.ExecuteNonQuery();
      con.Close();
      GridView1.EditIndex = -1;
      BindEmployeeDetails();
  }
  }
  catch(Exception ex)       
  {
      //do exception handling here. 
  }
}

哪一行给您带来了错误?一个好的做法是始终测试FindControl是否实际返回了某些内容。您能告诉行号错误的来源吗?添加:A)使用参数化SQL;b) 使用SQL操作的
语句来清理资源。@Nithesh con不能是罪魁祸首,因为它在前一行中是打开的。如果该值为空,则会在前一行中给出错误。
protected void gvDetails_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
  try
  {
  int nmbr = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());
  TextBox name = (TextBox)GridView1.Rows[e.RowIndex].FindControl("names");
  TextBox dept = (TextBox)GridView1.Rows[e.RowIndex].FindControl("depts");
  TextBox quantity = (TextBox)GridView1.Rows[e.RowIndex].FindControl("quantitys");
  //do check that any of your controls here is not null
  if(name!=null && dept!=null && quantity !=null)
  {
      con.Open();
      SqlCommand cmds=new SqlCommand("update erbp set name ='" + name.Text + "',dept ='"+ 
          dept.Text+"',quantity='" + quantity.Text + "' where inmbr=" + nmbr , con);
      cmds.ExecuteNonQuery();
      con.Close();
      GridView1.EditIndex = -1;
      BindEmployeeDetails();
  }
  }
  catch(Exception ex)       
  {
      //do exception handling here. 
  }
}