2013-04-20 127 views
0

我得到NULLREFERENCEEXCEPTION在gridview更新查詢。爲什麼我在下面的代碼中獲得NULL EXCEPTION?

protected void GridView1_RowUpdating(Object sender, GridViewUpdateEventArgs e) 
{ 
    TextBox txtname = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtname1"); 
    cmd.Connection = con; 
    cmd.CommandText = "update test1 set Name='" + txtname.Text + "' where Roll_No = '" 
        + GridView1.DataKeys[e.RowIndex].Values[0].ToString() + "'"; 
    con.Open(); 
    int temp = cmd.ExecuteNonQuery(); 
    if (temp == 1) 
    { 
     Label1.Text = "Record updated sucessfully"; 
    } 
    GridView1.EditIndex = -1; 
    FillGrid(); 
    con.Close();   
} 
+0

請使用調試器來確定哪個東西是空的。代碼中有很多可能性,我們無法猜測。 – Mat 2013-04-20 09:35:30

+0

什麼樣的調試器? – 2013-04-20 09:38:18

+0

把你的gridview結構放在這裏。 – 2013-04-20 09:39:29

回答

0

有很多,但一些可能是

TextBox txtname = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtname1"); 

有行中沒有文本框。由於某種原因。

GridView1.DataKeys[e.RowIndex].Values[0].ToString() 

上面值爲空。

另一個原因可能是,你可能會在page_load結合它,而不是page_load (!Page.IsPostBack)

0

請確保您已經正確控制的名字和你的代碼檢查空

if(GridView1.Rows[e.RowIndex].FindControl("txtname1")!=null) 
{ 
    //your code 
} 

調試,看看它會產生異常。

0

使用它來調試它。

try{ 
TextBox txtname = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtname1"); 
cmd.Connection = con; 
cmd.CommandText = "update test1 set Name='" + txtname.Text + "' where Roll_No = '" + GridView1.DataKeys[e.RowIndex].Values[0].ToString() + "'"; 
con.Open(); 
int temp = cmd.ExecuteNonQuery(); 
if (temp == 1) 
{ Label1.Text = "Record updated sucessfully"; } 
else{Label1.Text = "Updating failure";} 
GridView1.EditIndex = -1; 
FillGrid(); 
con.Close(); 
} 
catch (Exception e) 
{ 
e.printStackTrace(); 
} 
0

嘗試使用此方法驗證的問題來源:

TextBox txtname = GridView1.Rows[e.RowIndex].FindControl("txtname1") as TestBox; 
    if(txtname is null) 
    { 
    Response.Write("Unable to find txtname"); 
    return; 
    } 

如果您的網格是在一個母版頁的的ContentPlaceHolder,那麼你的控件的ID會在運行時改變。您可以將文本框的「ClientIdMode」屬性設置爲「靜態」,以便在運行時ID保持不變。

+0

我收到了一個異常「無法找到txtname」 – 2013-04-20 09:55:27

+0

這是來自代碼的消息。將文本框「txtname1」的「ClientIDMode」屬性設置爲「靜態」,然後重試。 – 2013-04-20 09:57:12

+0

沒有使用母版頁 – 2013-04-20 09:57:27

相關問題