1 回答

TA貢獻1815條經驗 獲得超13個贊
嘗試像這樣更新代碼:
if (e.CommandName == "AddToCart") {
bool productExists = false;
Session["uid"] = 1;
Label lbl = (Label) e.Item.FindControl("PIDLabel");
lblAtC.Text = lbl.Text;
ShowMessage("Product successfully added to Cart", MessageType.Success);
string connStr = ConfigurationManager.ConnectionStrings["MWM1812ConnString"].ConnectionString;
SqlConnection conn = new SqlConnection(connStr);
conn.Open();
string sqlQuery = "SELECT * FROM tblShoppingCart WHERE uid=@uid AND pid=@pid";
SqlCommand comm = new SqlCommand(sqlQuery, conn);
comm.Parameters.AddWithValue("@uid", Session["uid"]);
comm.Parameters.AddWithValue("@pid", lblAtC.Text.Trim());
using(SqlDataReader reader = comm.ExecuteReader()) {
productExists = reader.HasRows;
}
if (productExists) {
string sqlQuery2 = "UPDATE tblShoppingCart SET qty=qty+1 WHERE uid=@uid AND pid=@pid";
// Add code for adding parameters and executing sqlQuery2
} else {
string sqlQuery1 = "INSERT INTO tblShoppingCart (uid, pid, qty, dtShopped) VALUES (@uid, @pid, @qty, @dtShopped)";
SqlCommand comma = new SqlCommand(sqlQuery, conn);
comma.Parameters.AddWithValue("@uid", Session["uid"]);
comma.Parameters.AddWithValue("@pid", lblAtC.Text);
comma.Parameters.AddWithValue("@qty", 1);
//comm.Parameters.AddWithValue("@dtShopped", DateTime.Now.ToLongDateString());
comma.Parameters.AddWithValue("@dtShopped", DateTime.Now.ToString());
int result = comma.ExecuteNonQuery();
}
}
注意使用 reader.HasRows 屬性來確定產品是否已經存在。此外,SqlDataReader 被包裝在using塊內以將其處理掉。
- 1 回答
- 0 關注
- 102 瀏覽
添加回答
舉報