.net c#购物车模块分析

http://blog.csdn.net/IHandler/article/details/5781662

  购物车的实现形式多样,在这里,我用到了虚拟表和sesson方法存储。
    首先创建一个商品的表,GridView控件绑定数据源。在GridView中添加一个列,控件为
buttonfield.在GridView的RowCommand事件写代码:
         DataTable cart = new DataTable();//新建虚拟表
        if (Session["shoppingcart"] == null)
        {
            cart.Columns.Add("pname", typeof(string));//编辑表的列的属性
            cart.Columns.Add("pid", typeof(string));
            cart.Columns.Add("price", typeof(string));
            Session["shoppingcart"] = cart;
        }
        cart = (DataTable)Session["shoppingcart"];
        int n = Convert.ToInt32(e.CommandArgument);
      string p1 = GridView1.Rows[n].Cells[0].Text;//获得商品的数据
      string p2 = GridView1.Rows[n].Cells[1].Text;
      string p3 = GridView1.Rows[n].Cells[2].Text;
        DataRow rr = cart.NewRow();
        rr["pname"] = p1;
        rr["pid"] = p2;
        rr["price"] = p3;
        cart.Rows.Add(rr);//增加一条记录
        
        Session["shoppingcart"] = cart;
购物车页面:添加一个未绑定数据源的GridView控件:一个显示总额的lable的控件。
在页面加载事件中写代码:
if (!this.IsPostBack){
        GridView1.DataSource = Session["shoppingcart"];
        GridView1.DataBind();
        double sum = 0.0;
        for (int i = 0; i < GridView1.Rows.Count; i++)
        {
           
         sum = sum + (double.Parse(GridView1.Rows.Cells[2].Text));
           
        }
        Label2.Text ="总计:"+ sum.ToString()+"元";
        }
这样显示GridView控件了虚拟表的数据并且把总共的金额进行了加总。
增添两个按钮控件:清空   提交订单
清空按钮代码:

        Session.Remove("shoppingcart");
        GridView1.DataBind();
        Label2.Text = "总计:0元";
提交订单:这里是提交给数据库,建一个订单表。
事件代码:
        string name = Session["sa"].ToString();//获得提交用户的用户名
        double sum = 0.0;
        string p1="";
        string p2="";
        for (int i = 0; i < GridView1.Rows.Count; i++)
        {
         sum = sum + (double.Parse(GridView1.Rows
.Cells[2].Text));
          p1 =p1+"、" + GridView1.Rows.Cells[0].Text;
          p2 =p2 +"、"+ GridView1.Rows
.Cells[1].Text;
           }
        
        DataClasses3DataContext w = new DataClasses3DataContext();
        dingdan dan = new dingdan();
        dan.username = name;
        dan.dingdan1= p1+p2;
        dan.price = sum.ToString();
        dan.addtime = Convert.ToDateTime(DateTime.Now);
        w.dingdans.InsertOnSubmit(dan);
        w.SubmitChanges();
点击清空:

提交订单后,订单查看:

 这里的还很粗糙,代码很多需要完善。

 

.Net用Cookie做购物车

public class ShoppingCart
    {
       //保存购物车ID和数量到Cookie中

//保存ID的格式:"1,32,43

//下面是对应数量:"2,3,2"

如ID=1,对应的数量就是2
       public void SaveCookieCart(int productId, int amount)
       {
        
           if (HttpContext.Current.Request["ShoppingCart"]== null)
           {
               HttpCookie cookie = new HttpCookie("ShoppingCart");
               DateTime dt = DateTime.Now;
               TimeSpan ts = new TimeSpan(7, 0, 0, 0, 0);

               cookie.Values.Add("ProductId",productId.ToString());
               cookie.Values.Add("Amount", amount.ToString());
               HttpContext.Current.Response.AppendCookie(cookie); cookie.Expires = dt.Add(ts);
           }
           else
           {
               //用逗号隔开
               HttpCookie cookie = HttpContext.Current.Request.Cookies["ShoppingCart"];
               string[] ProductIdArray = cookie["ProductId"].ToString().Split(',');
               string[] Amount = HttpContext.Current.Request.Cookies["ShoppingCart"]["Amount"].ToString().Split(',');
               if (!ProductIdArray.Contains(productId.ToString()))
               {
                   cookie.Values["ProductId"] = HttpContext.Current.Request.Cookies["ShoppingCart"]["ProductId"] + "," + productId;
                   cookie.Values["Amount"] = HttpContext.Current.Request.Cookies["ShoppingCart"]["Amount"] + "," + amount;
                }  
                 HttpContext.Current.Response.AppendCookie(cookie);
                   DateTime dt = DateTime.Now;
                   TimeSpan ts = new TimeSpan(7, 0, 0, 0, 0);
                   cookie.Expires = dt.Add(ts);
             
           }
       }
       //购物车数据源,也可以作为订单数据源
       public IList<Model.ShoppingCartProduct> GetIListShoppingCartFromCookie()
       {
           HttpCookie cookie = HttpContext.Current.Request.Cookies["ShoppingCart"];
           if (cookie != null)
           {
               string[] ProductIdArray = cookie["ProductId"].ToString().Split(',');
               string[] AmountArray = cookie["Amount"].ToString().Split(',');
               int productId;
               int amount;
               IList<Model.ShoppingCartProduct> iList = new List<Model.ShoppingCartProduct>();
               for (int i = ProductIdArray.Length-1; i >= 0; i--)
               {
                   productId = Convert.ToInt32(ProductIdArray[i]);
                   amount = Convert.ToInt32(AmountArray[i]);
                   Model.ShoppingCartProduct shoppingCart = new SqlDAL.ShoppingCart().GetShoppingCartItem(productId,amount);
                   iList.Add(shoppingCart);           
               }
               return iList;
           }
           else{
               return null;          
           }
       }
       //删除购物车中的某一项
       public void DeleteShoppingCartCookieItem(int productId)
       {
           HttpCookie cookie = HttpContext.Current.Request.Cookies["ShoppingCart"];
         
           if (cookie != null)
           {
               string[] ProductIdArray = cookie["ProductId"].ToString().Split(',');
               string[] AmountArray = cookie["Amount"].ToString().Split(',');
                             StringBuilder productIdCookie=new StringBuilder();
               StringBuilder amountCookie = new StringBuilder();
               for (int i =0; i<ProductIdArray.Length; i++)
               {
                   string productIdItem=ProductIdArray[i].Trim();
                   string amountItem=AmountArray[i].Trim();
                   //如果不相等就保存
                   if(productId.ToString()!=productIdItem){  
                      
                 
                   productIdCookie.Append(productIdItem+",");//追加完成
                   amountCookie.Append(amountItem+",");//追加完成
                   }
               }
                 //更新删除Id后的COOKIE
                   cookie.Values["ProductId"] = productIdCookie.ToString().Substring(0, productIdCookie.Length-1);
                   cookie.Values["Amount"] =amountCookie.ToString().Substring(0,amountCookie.Length-1);
                   HttpContext.Current.Response.AppendCookie(cookie);
                   DateTime dt = DateTime.Now;
                   TimeSpan ts = new TimeSpan(7, 0, 0, 0, 0);
                   cookie.Expires = dt.Add(ts);

           }
       }
       //清空购物车
       public void ClearCookie()
       {

           if (HttpContext.Current.Request["ShoppingCart"] != null)
           {
               HttpCookie cookie = new HttpCookie("ShoppingCart");
               DateTime dt = DateTime.Now;
               TimeSpan ts = new TimeSpan(0, 0, 0, 0, 0);
               cookie.Values.Add("ProductId", "");
               cookie.Values.Add("Amount", "");
               HttpContext.Current.Response.AppendCookie(cookie); cookie.Expires = dt.Add(ts);
           }

       }
       //修改购物车某商品的数量
       public void ModifyAmount(int productId,int amount)
       {
           HttpCookie cookie = HttpContext.Current.Request.Cookies["ShoppingCart"];
           if (cookie != null)
           {
               string[] ProductIdArray = cookie["ProductId"].ToString().Split(',');
               string[] AmountArray = cookie["Amount"].ToString().Split(',');
             
               StringBuilder productIdCookie = new StringBuilder();
               StringBuilder amountCookie = new StringBuilder();
               for (int i = 0; i < ProductIdArray.Length; i++)
               {
                 
                   //如果不相等就保存
                   if (productId.ToString()==ProductIdArray[i].ToString())
                   {


                       productIdCookie.Append(ProductIdArray[i]+ ",");
                       amountCookie.Append(amount + ",");//修改操作
                   }
                   else
                   {
                       productIdCookie.Append(ProductIdArray[i] + ",");//追加完成
                       amountCookie.Append(AmountArray[i] + ",");//追加完成
                   }
               }
               //更新删除Id后的COOKIE
               cookie.Values["ProductId"] = productIdCookie.ToString().Substring(0, productIdCookie.Length - 1);
               cookie.Values["Amount"] = amountCookie.ToString().Substring(0, amountCookie.Length - 1);//删除最后的逗号
               HttpContext.Current.Response.AppendCookie(cookie);
               DateTime dt = DateTime.Now;
               TimeSpan ts = new TimeSpan(7, 0, 0, 0, 0);
               cookie.Expires = dt.Add(ts);
         
           }
          
       }


    }
}

 

.netc#购物车 代码系列3
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Web.UI.HtmlControls; 
using System.Data; 
using DAO; 
using System.Drawing; 
public partial class ShoppingCart : System.Web.UI.Page 

    //整型变量,用于存储总金额  
    private Int32 Total = 0; 
    protected void Page_Load(object sender, EventArgs e) 
    { 
        if (!IsPostBack) 
        { 
            BindCartList(); 
        } 
    } 
    private void BindCartList() 
    { 
        DataTable dt = new DataTable(); 
        //如果Session变量存在,则直接获取  
        if (Session["Cart"] != null) 
        { 
            dt = (DataTable)Session["Cart"]; 
        } 
        else//如果Session变量不存在,创建存储数据的表结构  
        { 
            dt.Columns.Add(new DataColumn("ID", typeof(Int32))); 
            dt.Columns.Add(new DataColumn("ProductNo", typeof(String))); 
            dt.Columns.Add(new DataColumn("ProductName", typeof(String))); 
            dt.Columns.Add(new DataColumn("BuyPrice", typeof(String))); 
            dt.Columns.Add(new DataColumn("Amount", typeof(Int32))); 
        } 
        //ID或ProductNo不为null  
        //则表示选中一件商品添加到购物车  
        if (ID != null) 
        { 
            //先判断购物车中是否已经存在该商品  
            Boolean IsExist = false; 
            foreach (DataRow dr in dt.Rows) 
            { 
                if (dr["ProductNo"].ToString() == ProductNo) 
                { 
                    IsExist = true; 
                    break; 
                } 
            } 
            //如果购物车中存在该商品,则提示客户  
            //该商品不会被重复添加到购物车  
            if (IsExist) 
            { 
                ScriptManager.RegisterStartupScript( 
                    this, typeof(Page), "alertExist", "alert('您选择的商品(编号:" + ProductNo + ")已在购物车存在!')", true); 
            } 
            else//如果购物车中不存在该商品,则添加到购物车  
            { 
                SqlHelper helper = new SqlHelper(); 
                DataTable dtRow = helper.FillDataTable( 
                    String.Format("Select * From Products Where ID={0}", ID.ToString())); 
                dt.Rows.Add(new object[]{ 
                    Convert.ToInt32(ID.ToString()), 
                    dtRow.Rows[0]["ProductNo"].ToString(), 
                    dtRow.Rows[0]["ProductName"].ToString(), 
                    Convert.ToInt32(dtRow.Rows[0]["BuyPrice"].ToString()), 
                    1}); 
            } 
        } 
        gvCart.DataSource = dt; 
        gvCart.DataBind(); 
        Session["Cart"] = dt; 
    } 
    protected void gvCart_RowDataBound(object sender, GridViewRowEventArgs e) 
    { 
        if (e.Row.RowType == DataControlRowType.DataRow) 
        { 
            //GridView行的加亮显示功能  
            e.Row.Attributes.Add("onmouseover", "b=this.style.backgroundColor;this.style.backgroundColor='#E1ECEE'"); 
            e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=b"); 
            //给+号图片和-号图片添加客户端click事件  
            //用JavaScript实现数量的+1和-1  
            TextBox tb = (TextBox)e.Row.FindControl("txtAmount"); 
            ((HtmlImage)e.Row.FindControl("imgReduce")).Attributes.Add("onclick", "Reduce(" + tb.ClientID + ")"); 
            ((HtmlImage)e.Row.FindControl("imgPlus")).Attributes.Add("onclick", "Plus(" + tb.ClientID + ")"); 
             
            //根据商品单价和数量计算购物车中商品的总金额  
            DataRowView drv = (DataRowView)e.Row.DataItem; 
            Total += Int32.Parse(drv["BuyPrice"].ToString())*Int32.Parse(tb.Text); 
        } 
        if (e.Row.RowType == DataControlRowType.Footer) 
        { 
            //将总金额显示在金额一列对应的Footer单元格  
            e.Row.Cells[1].Text = "金额总计:"; 
            e.Row.Cells[1].HorizontalAlign = HorizontalAlign.Right; 
            e.Row.Cells[2].Text = Total.ToString("c2"); 
            e.Row.Cells[2].ForeColor = Color.Red; 
        } 
    } 
    protected void gvCart_RowDeleting(object sender, GridViewDeleteEventArgs e) 
    { 
        //点击删除时从DataTable中删除对应的数据行  
        if (Session["Cart"] != null) 
        { 
            DataTable dt = (DataTable)Session["Cart"]; 
            dt.Rows.RemoveAt(e.RowIndex); 
            dt.AcceptChanges(); 
            Session["Cart"] = dt; 
            Response.Redirect("ShoppingCart.aspx"); 
        } 
    } 
    protected void imgbtnTotal_Click(object sender, ImageClickEventArgs e) 
    { 
        //遍历GridView,根据每行的文本框中的值  
        //修改DataTable中对应行中数量一列的值  
        if (Session["Cart"] != null) 
        { 
            DataTable dt = (DataTable)Session["Cart"]; 
            for (int i = 0; i < gvCart.Rows.Count; i++) 
            { 
                dt.Rows[i]["Amount"] = ((TextBox)gvCart.Rows[i].FindControl("txtAmount")).Text; 
            } 
            dt.AcceptChanges(); 
            Session["Cart"] = dt; 
            Response.Redirect("ShoppingCart.aspx"); 
        } 
    } 
    #region 属性  
    /// <summary>  
    /// get URL参数ID的值,定义为Nullable<Int32>类型  
    /// </summary>  
    private Int32? ID 
    { 
        get 
        { 
            try 
            { 
                return Int32.Parse(Request.QueryString["ID"]); 
            } 
            catch 
            { 
                return null; 
            } 
        } 
    } 
    /// <summary>  
    /// get URL参数ProductNo的值  
    /// </summary>  
    private String ProductNo 
    { 
        get 
        { 
           return Request.QueryString["ProductNo"]; 
        } 
    } 
    #endregion  

posted @ 2011-07-08 18:27  天涯海客  阅读(1994)  评论(1编辑  收藏  举报