2013-07-20 179 views
-1

我得到了下面的錯誤信息,而更新的GridView控件的值:更新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

哪條線是給你的錯誤? – Ehsan

+0

一個好的做法是總是測試FindControl是否實際返回一些東西。 – melancia

+0

你能告訴錯誤發生的行號嗎 – nrsharma

回答

0

你需要更新你的代碼來檢查你已經從gridview分配的控件不爲null。做一些異常處理。

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. 
    } 
}