-1

I got the below error message while updating the value on the gridview:

"Object reference not set to an instance of an object"

And my c# code is:

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();
}
Nithesh Narayanan
  • 11,481
  • 34
  • 98
  • 138
ram
  • 117
  • 2
  • 3
  • 6

1 Answers1

0

you need to update your code to check that controls that you have assigned from gridview are not null. Do some exception handling as well.

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. 
  }
}
Ehsan
  • 31,833
  • 6
  • 56
  • 65