2011-04-14 87 views
0

我試圖更新基於我的數據庫中的列或不在GridView中檢查複選框。此更新僅在button_click後發生。問題可能是我的語法,所以如果有人能糾正我,那將非常感激。根據複選框的值更新列

看到這裏我的代碼:

protected void ButtonAfTeHalen_Click(object sender, EventArgs e) 
    { 
     foreach (GridViewRow r in GridViewOrders.Rows) 
     { 
      if (((CheckBox)r.Cells[0].FindControl("CheckBoxATH")).Checked == true 
         && (Label)r.Cells[3].FindControl("LabelOrderID") != null) 
      { 
       string conn2 = "Data Source=pc-..."; 
       CheckBox checkBoxATH = (CheckBox)GridViewOrders.FindControl("CheckBoxATH"); 
       Label orderID = (Label)r.Cells[3].FindControl("LabelOrderID"); 
       LabelTestID.Visible = true; 
       LabelTestID.Text = orderID.Text.ToString(); 

       System.Data.SqlClient.SqlConnection sqlConn10 = new System.Data.SqlClient.SqlConnection(conn2); 
       sqlConn10.Open(); 
       System.Data.SqlClient.SqlCommand updateCommand = 
        new System.Data.SqlClient.SqlCommand("UPDATE tblOrders SET Status= " + checkBoxATH.Checked + " WHERE [email protected]", sqlConn10); 
       updateCommand.Parameters.AddWithValue("@orderID", LabelTestID.Text); 
       updateCommand.ExecuteNonQuery(); 
      } 
     } 
    } 

錯誤說:對象引用不設置到對象的實例。

錯誤@更新語句。但它確實在標籤上顯示訂單的ID。只有gridview中最低檢查順序的ID tho,不是所有選定的ID。

Regards Mati

+0

檢查空的checkBoxATH,訂單ID以及您是否在找control.And提供有效的值也告訴我們行你得到這個錯誤。 – varadarajan 2011-04-14 08:24:24

+0

看來你並沒有使用'GridViewRow r'變量。 – jfs 2011-04-14 08:25:52

+0

@jfs:true,if if(((CheckBox)r.Cells [0] .FindControl(「CheckBoxATH」))。Checked == true) {}'在我的代碼中,問題依然存在。 Still Object not set to ... – Dieter 2011-04-14 08:33:17

回答

1

嘿,我已經找到了解決辦法。這裏是我的代碼(投票,如果你喜歡;))

 for (int i = 0; i < GridViewOrder.Rows.Count; i++) 
     { 
      CheckBox ck = (CheckBox)GridViewOrder.Rows[i].Cells[0].FindControl("CheckBoxATH"); 
      Label orderID = (Label)GridViewOrder.Rows[i].Cells[5].FindControl("LabelOrderID"); 

      if (ck != null) 
      { 
       string conn = "Data Source=pc-..."; 
       System.Data.SqlClient.SqlConnection sqlConn = new System.Data.SqlClient.SqlConnection(conn); 
       sqlConn.Open(); 
       System.Data.SqlClient.SqlCommand updateCommand = new System.Data.SqlClient.SqlCommand("UPDATE tblOrders SET tOrderATH = '" + ck.Checked + "' WHERE tOrderId= '" + orderID.Text + "'", sqlConn); 
       updateCommand.Parameters.AddWithValue("@orderID", orderID.Text); 
       updateCommand.ExecuteNonQuery(); 
      } 
     } 
0

聽起來像是空引用給我。檢查更新語句中使用的所有引用,並確保它們不爲空。

//丹尼爾

0

我也面臨同樣的問題。我解決了它這種方式,希望它也能解決您的概率..

 if ((Boolean)((DataGridViewCheckBoxCell)r.Cells[0].FindControl("CheckBoxATH").FormattedValue) 
&& (Label)r.Cells[3].FindControl("LabelOrderID") != null) 

在這裏,我已經使用FormattedValue的,因爲該複選框的狀態不改變比它給出了一個空值。

在一個神祕的方式datagridview的複選框電池的工作原理,如果複選框被選中相比有時它給出的值true或有時它給出的值檢查...

+0

在這裏,我不知道你爲什麼使用findcontrol,當你可以直接在單元[「CheckBoxATH」]給「CheckBoxATH」... – 2011-04-14 11:36:53

+0

謝謝你的努力,但這段代碼不會爲我工作,因爲我使用一個GridView,而不是DataGridView,它也不會識別.FormattedValue。 – Dieter 2011-04-14 12:06:16