2015-11-28 25 views
0

試圖獲取一個gridview來檢查複選框的每一行,然後將該記錄添加到「購物車」表中,如果它被選中。邏輯被設置爲在用戶點擊按鈕時觸發。我知道在每個循環中打開和關閉可能效率不高,但我不能想到用另一種方法來完成它,並且仍然使用每個循環修改參數。 DataDirectory目錄| |oledbcommand在每行執行時遇到困難

protected void ShoppingCartButton_Click(object sender, EventArgs e) 
{ 
//set up connectionstring and oledbconnection 
    OleDbConnection myconn = new OleDbConnection(); 
     myconn.ConnectionString =  "Provider=Microsoft.ACE.OLEDB.12.0;Data  Source=|DataDirectory|\\ProjectDatabase.accdb"; 

    string UserID = Session["UserID"].ToString(); 
//retrieves the UserID for the session. If no userid is present, the  button won't be visible to the user(in page load) 

    foreach (GridViewRow row in GridView1.Rows) 
//checks row by row 
    { 
     string unpredictable = ""; 
//checks where a checkbox is checked 
     CheckBox chkCtrl1 = (CheckBox)row.FindControl("chkCtrl"); 
      if (chkCtrl1.Checked) 
      { //if it is, grabs the gameid and puts it into the string 
        unpredictable = row.Cells[1].Text; 
//declared the oledbcommand here 
       OleDbCommand cmd = new OleDbCommand(); 
//insert based on username and gameid 
cmd.CommandText = "insert into Cart ([Username],[GameID]) values (?,?)"; 
cmd.Parameters.AddWithValue("@Username", UserID); 
cmd.Parameters.AddWithValue("@GameID", unpredictable); 
//opens the connection and closes it with each loop 
myconn.Open(); 
cmd.ExecuteNonQuery(); 
myconn.Close(); 

      } 




    } 
+0

而且麻煩的是? –

+0

我應該詳細闡述。它不會保存到表 – Cambio

+0

而例外是? :)我認爲這裏的錯誤是INSERT語句中的參數名稱。你可以嘗試這個:「插入到購物車([用戶名],[遊戲ID])值(@用戶名,@遊戲ID)」; –

回答

0
  • 後刪除您連接字符串背面斜線。還要添加:providerName =「System.Data.OleDb」(可能不是必需的)。
  • 您的OleDbCommand不知道連接字符串。移動SQL轉換成字符串:

string sql = "insert into Cart ([Username],[GameID]) values (?,?)";

然後創建命令:

OleDbCommand cmd = new OleDbCommand(sql, myconn);