C#写购物车

这个主要用Session跟Hashtable,前面的就不写了,
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
namespace shop
{
 /// <summary>
 /// Addtocart 的摘要说明。
 /// </summary>
 public class Addtocart : System.Web.UI.Page
 {
  SqlConnection mycon;
  private void Page_Load(object sender, System.EventArgs e)
  {
   // 在此处放置用户代码以初始化页面
   string prod_id=Request.QueryString["prodID"].ToString();   
//   mycon=DB.mycon();
//   mycon.Open();  
   if(Session["bus"]==null)//如果是第一次购物,就生成新的hsahtable
   {
    System.Collections.Hashtable ht=new Hashtable();
    ht.Add(prod_id,1);//将商品的ID加到hashtable中
    Session["bus"]=ht;//用Session保存hasthtable
   }
   else//如果一开始有购物,则用以前的购物车,并加上最后买的商品
   {
    System.Collections.Hashtable ht=(Hashtable)Session["bus"];
    if(ht[prod_id]==null)
    {
     ht[prod_id]=1;
    }
    else
    {
     ht[prod_id]=(int)ht[prod_id]+1;
    }
    Session["bus"]=ht;
   }
   Response.Redirect("cart.aspx?storeID="+Request.QueryString["storeID"].ToString());//跳转到购物车的页面偶这个是一个大的商城,商城里还有小店,所以的再传个商店的ID
  }
  #region Web 窗体设计器生成的代码
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
   //
   InitializeComponent();
   base.OnInit(e);
  }
  
  /// <summary>
  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  /// </summary>
  private void InitializeComponent()
  {   
   this.Load += new System.EventHandler(this.Page_Load);
  }
  #endregion
 }
}
以上是只是个开始,正文刚开始,嘻嘻!!下面是购物车的主体部分!
  namespace shop
{
 using System;
 using System.Data;
 using System.Drawing;
 using System.Web;
 using System.Collections;
 using System.Web.UI.WebControls;
 using System.Web.UI.HtmlControls;
 using System.Data.SqlClient;
 
 /// <summary>
 ///  cartmain 的摘要说明。
 /// </summary>
 public class cartmain : System.Web.UI.UserControl
 {
  protected System.Web.UI.WebControls.DataList DataList1;
  protected System.Web.UI.WebControls.Label mon1;
  protected System.Web.UI.WebControls.Label mon;
  protected System.Web.UI.WebControls.Label count;
  protected System.Web.UI.WebControls.DataGrid bus;
  protected System.Web.UI.WebControls.LinkButton LinkButton1;
  protected System.Web.UI.WebControls.Label errmessage;
  protected System.Web.UI.WebControls.ImageButton ImageButton1;
  SqlConnection mycon;
  private void Page_Load(object sender, System.EventArgs e)
  {
   // 在此处放置用户代码以初始化页面
   if(!this.IsPostBack)
   {
    mycon=DB.mycon();
    mycon.Open();
    //绑定推荐的商店
    this.DataList1.DataSource=DB.mytable("select top 10 * from netstore where store_tj=1 order by builddate","netstore");
    this.DataList1.DataBind();
    CartBind();
    //重新计算价格
    CountMoney();
   }
  }
  //计算节省的钱
  public double reduce(double sc,double rm)
  {
   double sheng=sc-rm;
   return sheng;
  }
  public string getleft(string a)
  {
   string b=a;
   if(a.Length>8)
    b=a.Substring(0,8).ToString()+"...";
   return b;
  }
  public string getleft1(string a)
  {
   string b=a;
   if(a.Length>6)
    b=a.Substring(0,6).ToString()+"...";
   return b;
  }
  #region Web 窗体设计器生成的代码
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
   //
   InitializeComponent();
   base.OnInit(e);
  }
  
  /// <summary>
  ///  设计器支持所需的方法 - 不要使用代码编辑器
  ///  修改此方法的内容。
  /// </summary>
  private void InitializeComponent()
  {  
   this.LinkButton1.Click += new System.EventHandler(this.LinkButton1_Click);
   this.ImageButton1.Click += new System.Web.UI.ImageClickEventHandler(this.ImageButton1_Click);
   this.Load += new System.EventHandler(this.Page_Load);
  }
  #endregion
  //从hathtable里读取ID绑定在购物车上
  private void CartBind()
  {
   this.bus.DataSource=(Hashtable)Session["bus"];
   this.bus.DataBind();
   //绑定其它列
   BindOther();
   //重新计算价钱
   CountMoney();
  }
  //绑定DataGrid上的其它列
  private void BindOther()
  {
   for(int i=0; i<this.bus.Items.Count;i++)
   {
    mycon=DB.mycon();
    mycon.Open();
    SqlCommand cmd=new SqlCommand("select * from production where prod_id='"+this.bus.Items[i].Cells[1].Text+"'",mycon);
    SqlDataReader sdr=cmd.ExecuteReader();
    if(sdr.Read())
    {
     this.bus.Items[i].Cells[2].Text=sdr["prod_name"].ToString();
     this.bus.Items[i].Cells[3].Text=sdr["prod_scprice"].ToString();
     bus.Items[i].Cells[4].Text=sdr["prod_rmprice"].ToString();
     bus.Items[i].Cells[6].Text=sdr["prod_rmprice"].ToString();
     //获取购物品的数量,进行计算总价格
     TextBox num=(TextBox)bus.Items[i].Cells[5].FindControl("num");
     bus.Items[i].Cells[7].Text=Convert.ToString(Convert.ToDouble(bus.Items[i].Cells[6].Text)*Convert.ToDouble(num.Text));
     string storeID=Request.QueryString["storeID"].ToString();
    }
    cmd.Dispose();
    sdr.Close();
    mycon.Close();
   }
  }
  //更新购物车(当更改购物的数量或删除后的更新操作)
  private void UpdateCart()
  {
   //遍历bus并取得里面的所有的num和ckBox的值
   for(int c=0;c<bus.Items.Count;c++)
   {
    errmessage.Text="";
    TextBox num=(TextBox)bus.Items[c].FindControl("num");
    CheckBox ckBox=(CheckBox)bus.Items[c].FindControl("ckBox");
    try
    {
     if(int.Parse(num.Text)<0)
     {
      errmessage.Text="您至少有一项输入错误,请检查后重新输入!";
      return;
     }     
    }
    catch
    {
     errmessage.Text="您至少有一项输入错误,请检查后重新输入!";
     return;
    }
    //捕捉异常
    try
    {
     //获取选中的商品的ID号
     string PID=bus.Items[c].Cells[1].Text.ToString();
     int Num=int.Parse(num.Text.ToString());     
     //如果购买数量改变或者删除复选框被选中
     if(int.Parse(bus.DataKeys[c].ToString())!=Num||ckBox.Checked==true)
     {
      //判断如果数量为空或0或者删除复选框选中时就进行删除操作
      if(ckBox.Checked==true||Num==0)
      {     
       RemoveItem(PID);      
      }
      else
      {
       Hashtable ht=(Hashtable)Session["bus"];
       if(ht.Contains(PID))
       {
        RemoveItem(PID);
        UpdateHash(PID,Num.ToString());
       }
      }
     }
    }
    catch
    {
     errmessage.Text="您至少有一项输入错误";
    }
   }
  } 
  //删除操作的代码
  private void RemoveItem(string pID)
  {
   //从哈希表中移除所选中的要删除的物品
   Hashtable ht=(Hashtable)Session["bus"];
   ht.Remove(pID);  
   Session["bus"]=ht;
  } 
  //更新hashtable
  private void UpdateHash(string pID,string val)
  {
   Hashtable ht=(Hashtable)Session["bus"];
   ht.Add(pID,val);
   Session["bus"]=ht;
  } 
  //计算购物的总数量,总钱数以及打折后的钱数
  private void CountMoney()
  {
   int cou=0;
   double AllPrice=0;
   double money=0;
   for(int n=0;n<bus.Items.Count;n++)
   {
    //计算数量
    TextBox num1=(TextBox)bus.Items[n].Cells[5].FindControl("num");
    cou+=int.Parse(num1.Text);    
    //计算总钱数
    double price=double.Parse(bus.Items[n].Cells[3].Text);
    double num=double.Parse(num1.Text);    
    AllPrice+=(price*num);
    //打折后的钱数
    double allmon=double.Parse(bus.Items[n].Cells[7].Text);
    money+=allmon;
   }
   count.Text=cou.ToString();
   mon.Text=AllPrice.ToString();
   mon1.Text=money.ToString();
  } 
  private void LinkButton1_Click(object sender, System.EventArgs e)
  {
   
   //更新购物车
   UpdateCart();
   //进行绑定
   CartBind();   
  }
  private void ImageButton1_Click(object sender, System.Web.UI.ImageClickEventArgs e)
  {
   if(this.bus.Items.Count==0)
   {
    this.errmessage.Text="你还没有购买另何商品!!";
    return;
   }
   else
   {
    Response.Redirect("order.aspx?storeID="+Request.QueryString["storeID"]);
   }//这里就是转到订单的那个页!!
  }
  
 }
}
 
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
这里是一个简单的 C# 购物车的前端和后端代码示例: 后端代码(使用 ASP.NET MVC): ```csharp using System.Collections.Generic; using System.Linq; using System.Web.Mvc; namespace ShoppingCart.Controllers { public class HomeController : Controller { // 商品列表 private static readonly List<Product> Products = new List<Product> { new Product {Id = 1, Name = "商品1", Price = 10}, new Product {Id = 2, Name = "商品2", Price = 20}, new Product {Id = 3, Name = "商品3", Price = 30}, new Product {Id = 4, Name = "商品4", Price = 40}, new Product {Id = 5, Name = "商品5", Price = 50}, }; // 购物车 private static readonly List<CartItem> CartItems = new List<CartItem>(); public ActionResult Index() { // 把商品列表传递给前端页面 ViewBag.Products = Products; return View(); } // 添加商品到购物车 public ActionResult AddToCart(int id) { var product = Products.FirstOrDefault(p => p.Id == id); if (product != null) { // 查找购物车里是否已经有该商品,有则数量加 1,否则添加一条新的购物车项 var cartItem = CartItems.FirstOrDefault(ci => ci.Product.Id == product.Id); if (cartItem != null) { cartItem.Quantity++; } else { CartItems.Add(new CartItem {Product = product, Quantity = 1}); } } return RedirectToAction("Index"); } // 清空购物车 public ActionResult ClearCart() { CartItems.Clear(); return RedirectToAction("Index"); } } // 商品类 public class Product { public int Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } } // 购物车项类 public class CartItem { public Product Product { get; set; } public int Quantity { get; set; } } } ``` 前端代码: ```html @{ ViewBag.Title = "购物车"; } <h2>商品列表</h2> <ul> @foreach (var product in ViewBag.Products) { <li>@product.Name - ¥@product.Price <a href="@Url.Action("AddToCart", new {id = product.Id})">加入购物车</a></li> } </ul> <h2>购物车</h2> @if (HomeController.CartItems.Count == 0) { <p>购物车是空的</p> } else { <ul> @foreach (var cartItem in HomeController.CartItems) { <li>@cartItem.Product.Name - ¥@cartItem.Product.Price - 数量:@cartItem.Quantity</li> } </ul> <p><a href="@Url.Action("ClearCart")">清空购物车</a></p> } ``` 这里的代码实现了一个简单的购物车功能,包括商品列表、添加商品到购物车、清空购物车等功能。当用户点击“加入购物车”按钮时,会将商品添加到后端的购物车列表中;当用户查看购物车时,会从后端获取购物车列表并显示在前端页面上。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值