2013-05-15 30 views
0
protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e1) 
    { 
     if (e1.CommandName == "BuyClick") 
     { 
      Label iid_lbl = (Label)e1.Item.FindControl("iid_lbl"); 
      Label igid_lbl = (Label)e1.Item.FindControl("igid_lbl"); 
      Label iname_lbl = (Label)e1.Item.FindControl("iname_lbl"); 
      Label idesp_lbl = (Label)e1.Item.FindControl("idesp_lbl"); 
      Label iqty_lbl = (Label)e1.Item.FindControl("iqty_lbl"); 
      Label iprice_lbl = (Label)e1.Item.FindControl("iprice_lbl"); 
      Button Button1 = (Button)e1.Item.FindControl("Button1"); 
      str1 = "insert into orders values(' ',' ','" + igid_lbl.Text + "',' ',' ','" + iname_lbl.Text + "',' ')"; 
      str2 = "insert into order_item values(' ','" + iid_lbl.Text + "','" + idesp_lbl.Text + "',' ','" + iprice_lbl.Text + "','" + iqty_lbl.Text + "','" + iname_lbl.Text + "')"; 
      cmd1 = new MySqlCommand(str1, con1); 
      cmd2 = new MySqlCommand(str2, con1); 
      cmd1.ExecuteNonQuery(); 
      cmd2.ExecuteNonQuery(); 
      con1.Close(); 
      Response.Redirect("buy.aspx"); 
     } 

    } 

錯誤發生的實例在str1 = "insert into orders values(' ',' ','" + igid_lbl.Text + "',' ',' ','" + iname_lbl.Text + "',' ')";System.NullReferencedException發生。對象引用不設置到對象

+0

注意:你應該避免構建這樣的查詢。很難閱讀(並且維護)並且絕對不安全(SQL注入)。使用諸如'@ itemName'之類的參數,然後使用'MySqlCommand'參數替換它。 –

回答

0

行看起來像你想的網格/數據列表中訪問文本框。

如果是這種情況,那麼它不能以您嘗試去做的方式訪問。

您需要從網格中提取文本框/標籤。

事情是這樣的:

if(e.Row.RowType == DataControlRowType.DataRow && e1.CommandName == "BuyClick") { 
    Label igid = (Label)e.Row.FindControl("igid_lbl"); 
    Label iName = (Label)e.Row.FindControl("iname_lbl"); 

    // Do this for ALL your labels/textfields 

    // now your inserts should reference these labels. Such as 
    String str1 = "insert into orders values(' ',' ','" + igid.Text + "',' ',' ','" + iName.Text + "',' ')"; 

// ETC ETC ETC 

} 
+0

即使這也是得到一個錯誤..同行 – Sunil

+0

你需要把一個斷點,看看究竟什麼是空... – Darren

+0

亞..我看到str1爲空 – Sunil

0

請確保您正確命名的標籤,如果標籤不存在,則有可能導致串聯空到可能導致錯誤的字符串。

相關問題