无法让 oledbcommand 按行执行

Having trouble getting oledbcommand to execute on a per row basis

尝试让 gridview 检查每一行的复选框,然后将该记录添加到 "cart" table(如果选中)。该逻辑设置为在用户单击按钮时触发。我知道在每个循环中打开和关闭可能效率不高,但我想不出另一种方法来做到这一点并且仍然在每个循环中修改参数。

 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();

           }




    }
  • 从 |DataDirectory| 后的连接字符串中删除反斜杠。还添加:providerName="System.Data.OleDb"(可能不需要)。
  • 您的 OleDbCommand 不知道连接字符串。将 sql 移动到字符串中:

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

然后创建命令:

OleDbCommand cmd = new OleDbCommand(sql, myconn);