日期:2014-05-17  浏览次数:20412 次

ASP.net 求助
protected void createOrder(string orderid, string uname)
  {
  string cnnstr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
  SqlConnection connection = new SqlConnection(cnnstr);
  connection.Open();
  string cmdstr = "insert into orders(orderId,uname,date,totalPrice,status) values(@orderId,@uname,@date,@totalPrice,@status)";
  SqlCommand sqlcmd = new SqlCommand(cmdstr, connection);
  sqlcmd.Parameters.AddWithValue("@uname", uname);
  sqlcmd.Parameters.AddWithValue("@orderId", orderid);
  sqlcmd.Parameters.AddWithValue("@date", DateTime.Now.ToString());
  sqlcmd.Parameters.AddWithValue("@totalPrice", lblTotalPrice.Text);
  sqlcmd.Parameters.AddWithValue("@status", "未付款");
  SqlTransaction tran = null;
  try
  {
  connection.Open();
  //开启一个事务,并返回给tran
  tran = connection.BeginTransaction();
  sqlcmd.Transaction = tran;//指定sqlcmd对象属于tran事务
  sqlcmd.ExecuteNonQuery();//插入记录(生成订单)
  //向订单明细表中插入记录
  cmdstr = "insert into orderDetails(orderid,pid,number,totalprice) values(@orderid,@pid,@number,@totalprice)";
  sqlcmd.CommandText = cmdstr;
  Label lblPrice, lblPid;
  TextBox txtNumber;
  //将购买的商品的信息一一添加到订单明细表中
  for (int i = 0; i < ListView1.Items.Count; i++)
  {
  CheckBox ch = ListView1.Items[i].FindControl("CheckBox1") as CheckBox;
  if (ch.Checked)
  {
  lblPrice = ListView1.Items[i].FindControl("totalPriceLabel") as Label;
  lblPid = ListView1.Items[i].FindControl("pidLabel") as Label;
  txtNumber = ListView1.Items[i].FindControl("txtNum") as TextBox;
  sqlcmd.Parameters.Clear();//清空原来的sql参数,以便重新加入
  sqlcmd.Parameters.AddWithValue("@pid", lblPid.Text);
  sqlcmd.Parameters.AddWithValue("@orderid", orderid);
  sqlcmd.Parameters.AddWithValue("@number", txtNumber.Text);
  sqlcmd.Parameters.AddWithValue("@totalprice", lblPrice.Text);
  sqlcmd.ExecuteNonQuery();//插入记录(生成订单详细)
  sqlcmd.CommandText = "delete from shoppingcart where uname='" + uname + "' and pid=@pid";
  sqlcmd.Parameters.Clear();
  sqlcmd.Parameters.AddWithValue("@pid", lblPid.Text);
  sqlcmd.ExecuteNonQuery();//删除当用顾客的购物车中的信息
  }
  }
  /*sqlcmd.CommandText = "delete from shoppingcart where uname='" + uname +"'";
  sqlcmd.ExecuteNonQuery();//删除当用顾客的购物车中的信息*/
  tran.Commit();//提交事务
  //Page.RegisterStartupScript("kk", "<script>alert('生成成功')</script>");
  Response.Redirect("showorder.aspx");//转到查看订单页面
  }
  catch (Exception ex)//出错时
  {
  //回滚事务,数据库不作任务修改
  tran.Rollback();
  Page.RegisterStartupScript("kk", "<script>alert('出错')<