尝试让gridview检查每一行的复选框,然后将该记录添加到"购物车"如果检查表。当用户单击按钮时,逻辑设置为触发。我知道打开和关闭每个循环可能效率不高,但是我无法想到另一种方法,并且仍然会在每个循环中修改参数。
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)
string sql = "insert into Cart ([Username],[GameID]) values (?,?)";
然后创建命令:
OleDbCommand cmd = new OleDbCommand(sql, myconn);