-1

更新 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();
}
4

1 回答 1

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. 
  }
}
于 2013-07-20T10:46:05.797 回答