更新gridview时出错?

时间:2013-07-20 09:53:32

标签: c# asp.net .net gridview nullreferenceexception

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

  

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

我的c#代码是:

protected void gvDetails_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    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");
    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();
}

1 个答案:

答案 0 :(得分:0)

您需要更新代码以检查从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. 
  }
}