购物车的实现及结算处理

本示例利用Session对象来实现一个简单的购物车。主要用于教学演示。

Book类
此类主是代表购物车的一本书
using System;

namespace CartTest
{
 /// <summary>
 /// Books 的摘要说明。
 /// </summary>
 public class Book
 {
  string bookid;
  string title;
  decimal price;
  int num;


  public Book()
  {
  }

  /// <summary>
  /// ID
  /// </summary>
  public string BookID
  {
   get{return bookid;}
   set{bookid=value;}
  }
  /// <summary>
  /// 书名
  /// </summary>
  public string Title
  {
   get{return title;}
   set{title=value;}
  }
  
  /// <summary>
  /// 金额
  /// </summary>
  public decimal Price
  {
   get{return price;}
   set{price=value;
   sum=price*num;
   }
  }
  /// <summary>
  /// 数量
  /// </summary>
  public int Num
  {
   get{return num;}
   set{num=value;
   sum=price*num;
   }
  }
  decimal sum=0m;
  //一种书的总金额
  public decimal Sum
  {
   get{return sum;}
   set{sum=value;}
  }
 }

}

//购物车集合
//Books 用户所有订购的书 ,实现IEnumerable接口,我们可以将其绑定到datagrid控件
using System;
using System.Collections;
namespace CartTest
{
 /// <summary>
 ///
 /// </summary>
 public class Books :IEnumerable 
 {
  Hashtable ht=null;
  public Books()
  {
   ht=new Hashtable();
   
  }

  public Books(int count)
  {
   ht=new Hashtable(count);
  }

  public void Add(Book b)
  {
   //如果集合中有相同ID的书,则对书的数量进行相加
   if(ht.ContainsKey(b.BookID))
   {
 ((Book)ht[b.BookID]).Num=((Book)ht[b.BookID]).Num+b.Num;
    
   }
   else
   {
    ht.Add(b.BookID,b);
   }
  }

  public void Remove(string bookid)
  {
   if(ht.ContainsKey(bookid))
   ht.Remove(bookid);
  }
//统计有多少种书
  public int Count
  {
   get
   {
    return ht.Count;
   }
  }

  public void Clear()
  {
   ht.Clear();
  }

  public Book this[string bookid]
  {
   get
   {
    if(ht.ContainsKey(bookid))
     return (Book)ht[bookid];
    return null;
   }
  }
  #region IEnumerable 成员

  public IEnumerator GetEnumerator()
  {
   // TODO:  添加 Books.GetEnumerator 实现
   return ht.Values.GetEnumerator();
  }

  #endregion
 }
}

 

//此页面主要是用于显示所有的书。用的是DataList来自定义显示模板。但是实际上可以使用DataGrid来处理。DataGrid也可以实现分页功能及自定义模板。只要将dDatagrid设为一个模板列,然后将DataList里的模板列代码Copy过去即可。
//此页面中每本书都要显示封面。这个问题我们可以通过一个过渡页来处理图片数据

<%@ Page language="c#" Codebehind="BookList.aspx.cs" AutoEventWireup="false" Inherits="CartTest.BookList" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
 <HEAD>
  <title>BookList</title>
  <meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
  <meta content="C#" name="CODE_LANGUAGE">
  <meta content="JavaScript" name="vs_defaultClientScript">
  <meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
  <LINK href="http://localhost/CartTest/StyleSheet1.css" type="text/css" rel="stylesheet">
 </HEAD>
 <body MS_POSITIONING="GridLayout">
  <form id="Form1" method="post" runat="server">
   <asp:datalist id="DataList1" style="Z-INDEX: 101; LEFT: 16px; POSITION: absolute; TOP: 56px" runat="server"
    DataKeyField="BookGuid" Width="650">
    <ItemTemplate>
     <TABLE id="Table14" cellSpacing="1" cellPadding="1" border="0">
      <TR>
       <TD>
        <a href='<%# "BookView.aspx?BookID="+DataBinder.Eval(Container, "DataItem.BookGuid") %>'>
  <!--imageview.aspx页面专用来处理书的图片-->    <asp:Image id=Image1 runat="server" Width="120px" Height="144px" ImageUrl='<%# "ImageView.aspx?imgid="+DataBinder.Eval(Container, "DataItem.BookGuid") %>'>
         </asp:Image>
        </a>
       </TD>
       <TD vAlign="top">
        <TABLE id="Table15" cellSpacing="1" cellPadding="1" width="300" border="1">
         <TR>
          <TD>书名:
           <asp:Label id=Label1 runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.BookTitle") %>'>
           </asp:Label></TD>
         </TR>
         <TR>
          <TD>图书简介:
           <asp:Label id=Label2 style="OVERFLOW: hidden; TEXT-OVERFLOW: ellipsis" runat="server" Width="496" Text='<%# "<nobr>"+DataBinder.Eval(Container, "DataItem.BookComment")+"/<nobr>"%>' Height="50px">
           </asp:Label></TD>
         </TR>
         <TR>
          <TD>金额:
           <asp:Label id=Label3 runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.Price","{0:C}") %>'>
           </asp:Label></TD>
         </TR>
        </TABLE>
       </TD>
      </TR>
      <TR>
       <TD>
        <asp:Label id="Label4" runat="server">日期:</asp:Label>
        <asp:Label id=Label5 runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.PublishDate", "{0:D}") %>'>
        </asp:Label></TD>
       <TD align="right">
        <asp:ImageButton id="Imagebutton1" runat="server" ImageUrl="a.gif" CommandName="AddCart"></asp:ImageButton></TD>
      </TR>
     </TABLE>
    </ItemTemplate>
    <AlternatingItemTemplate>
     <TABLE id="Table4" cellSpacing="1" cellPadding="1" bgColor="#eefeff" border="0">
      <TR>
       <TD>
        <a href='<%# "BookView.aspx?BookID="+DataBinder.Eval(Container, "DataItem.BookGuid") %>'>
 <!--imageview.aspx页面专用来处理书的图片-->        <asp:Image id=Image2 runat="server" Width="120px" Height="144px" ImageUrl='<%# "ImageView.aspx?imgid="+DataBinder.Eval(Container, "DataItem.BookGuid") %>'>
         </asp:Image></a></TD>
       <TD vAlign="top">
        <TABLE id="Table5" cellSpacing="1" cellPadding="1" width="300" border="1">
         <TR>
          <TD>书名:
           <asp:Label id=Label6 runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.BookTitle") %>'>
           </asp:Label></TD>
         </TR>
         <TR>
          <TD>图书简介:
           <asp:Label id=Label7 style="OVERFLOW: hidden; TEXT-OVERFLOW: ellipsis" runat="server" Width="496px" Text='<%# DataBinder.Eval(Container, "DataItem.BookComment") %>' Height="50px">
           </asp:Label></TD>
         </TR>
         <TR>
          <TD>金额:
           <asp:Label id=Label8 runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.Price") %>'>
           </asp:Label></TD>
         </TR>
        </TABLE>
       </TD>
      </TR>
      <TR>
       <TD>
        <asp:Label id="Label9" runat="server">日期:</asp:Label>
        <asp:Label id=Label10 runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.PublishDate") %>'>
        </asp:Label></TD>
       <TD align="right">
        <asp:ImageButton id="Imagebutton2" runat="server" ImageUrl="a.gif"></asp:ImageButton></TD>
      </TR>
     </TABLE>
    </AlternatingItemTemplate>
   </asp:datalist></form>
 </body>
</HTML>

//CS CODE
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 CartTest
{
 /// <summary>
 /// BookList 的摘要说明。
 /// </summary>
 public class BookList : System.Web.UI.Page
 {
  protected System.Web.UI.WebControls.DataList DataList1;
 
  private void Page_Load(object sender, System.EventArgs e)
  {
   if(!this.IsPostBack)
   {
    SqlConnection cn=new SqlConnection();
    cn.ConnectionString="server=.;uid=sa;pwd=;database=p1";
    cn.Open();
    SqlCommand cmd=new SqlCommand();
    cmd.Connection=cn;
    cmd.CommandText="select * from books ";
    SqlDataAdapter da=new SqlDataAdapter();
    da.SelectCommand=cmd;
    DataSet ds=new DataSet();
    da.Fill(ds);
    cn.Close();
    this.DataList1.DataSource=ds.Tables[0];
    this.DataBind();
   }
  }

  #region Web 窗体设计器生成的代码
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
   //
   InitializeComponent();
   base.OnInit(e);
  }
  
  /// <summary>
  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  /// </summary>
  private void InitializeComponent()
  {   
   this.DataList1.ItemCommand += new System.Web.UI.WebControls.DataListCommandEventHandler(this.DataList1_ItemCommand);
   this.Load += new System.EventHandler(this.Page_Load);

  }
  #endregion

  private void DataList1_ItemCommand(object source, System.Web.UI.WebControls.DataListCommandEventArgs e)
  {
  
   //用户选中一本书后,默认订一本书
   string bookGuid=this.DataList1.DataKeys[e.Item.ItemIndex].ToString();
   Book b=new Book();
   //首先获得自己的购物车
   Books bs=(Books)Session["MyCart"];
   b.BookID=bookGuid;
   b.Num=1;
   //根据ITEM的类型取值
   if(e.Item.ItemType==ListItemType.Item)
   {
    b.Price=Convert.ToDecimal(((Label)e.Item.FindControl("Label3")).Text.Substring(1));
    b.Title=((Label)e.Item.FindControl("Label1")).Text;
   }
   else if(e.Item.ItemType==ListItemType.AlternatingItem)
   {
    b.Price=Convert.ToDecimal(((Label)e.Item.FindControl("Label8")).Text.Substring(1));
    b.Title=((Label)e.Item.FindControl("Label6")).Text;
   }
   //将书加入到购物车
   bs.Add(b);
   Session["MyCart"]=bs;
   //打开购物车页面。
   Response.Write("<script>window.open('webform1.aspx')</script>");
  }

  
 }
}


//图片处理页
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 CartTest
{
 /// <summary>
 /// ImageView 的摘要说明。
 /// </summary>
 public class ImageView : System.Web.UI.Page
 {
 
  private void Page_Load(object sender, System.EventArgs e)
  {
   SqlConnection cn=new SqlConnection();
   cn.ConnectionString="server=.;uid=sa;pwd=;database=p1";
   cn.Open();
   SqlCommand cmd=new SqlCommand();
   cmd.Connection=cn;
   cmd.CommandText="select cover from books where bookguid='"+ this.Request.QueryString["imgid"].ToString() +"'";
   //cmd.CommandText="select cover from books where bookguid='350bc228-a12d-4c15-b8e0-1e625e40403e'";
   SqlDataAdapter da=new SqlDataAdapter();
   da.SelectCommand=cmd;
   DataSet ds=new DataSet();
   da.Fill(ds);
   cn.Close();
   Response.Clear();
   Response.ClearContent();
   Response.ContentType="Image/jpg";
   Response.BinaryWrite((byte[])ds.Tables[0].Rows[0][0]);

  }

  #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
 }
}

//当用户选取其中一本书时,获得用户当前选中书的ID,将此ID传到具体察看页面
<%@ Page language="c#" Codebehind="BookView.aspx.cs" AutoEventWireup="false" Inherits="CartTest.BookView" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
  <HEAD>
  <title>BookView</title>
  <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
  <meta name="CODE_LANGUAGE" Content="C#">
  <meta name="vs_defaultClientScript" content="JavaScript">
  <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
  </HEAD>
 <body MS_POSITIONING="GridLayout">
  <form id="Form1" method="post" runat="server">
   <FONT face="宋体">
    <asp:Label id="Label1" style="Z-INDEX: 101; LEFT: 32px; POSITION: absolute; TOP: 24px" runat="server"
     Width="302px" Height="35px"></asp:Label>
    <asp:Image id="Image1" style="Z-INDEX: 102; LEFT: 24px; POSITION: absolute; TOP: 72px" runat="server"
     Width="120px" Height="136px"></asp:Image>
    <asp:Label id="Label2" style="Z-INDEX: 103; LEFT: 192px; POSITION: absolute; TOP: 88px" runat="server"
     Width="280px"></asp:Label>
    <asp:Label id="Label4" style="Z-INDEX: 104; LEFT: 200px; POSITION: absolute; TOP: 128px" runat="server" Width="328px">Label</asp:Label>
<asp:Panel id=Panel2 style="Z-INDEX: 105; LEFT: 24px; POSITION: absolute; TOP: 220px" runat="server" Height="172px" Width="456px"></asp:Panel>
<asp:Label id=Label5 style="Z-INDEX: 106; LEFT: 200px; POSITION: absolute; TOP: 168px" runat="server" Width="336px">Label</asp:Label></FONT>
    
  </form>
 </body>
</HTML>

 

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 CartTest
{
 /// <summary>
 /// BookView 的摘要说明。
 /// </summary>
 public class BookView : System.Web.UI.Page
 {
  protected System.Web.UI.WebControls.Label Label1;
  protected System.Web.UI.WebControls.Image Image1;
  protected System.Web.UI.WebControls.Label Label2;
  protected System.Web.UI.WebControls.Label Label3;
  protected System.Web.UI.WebControls.TextBox TextBox1;
  protected System.Web.UI.WebControls.Label Label4;
  protected System.Web.UI.WebControls.Panel Panel2;
  protected System.Web.UI.WebControls.Label Label5;
  protected System.Web.UI.WebControls.Panel Panel1;
 
  private void Page_Load(object sender, System.EventArgs e)
  {
   if(!this.IsPostBack)
   {
    if(this.Request["BookID"]!=null)
    {
     this.Image1.ImageUrl="ImageView.aspx?imgid="+this.Request["BookID"].ToString();
     SqlConnection cn=new SqlConnection();
     cn.ConnectionString="server=.;uid=sa;pwd=;database=p1";
     cn.Open();
     SqlCommand cmd=new SqlCommand();
     cmd.Connection=cn;
     cmd.CommandText="select * from books where bookguid='"+ this.Request.QueryString["BookID"].ToString() +"'";
     //cmd.CommandText="select cover from books where bookguid='350bc228-a12d-4c15-b8e0-1e625e40403e'";
     SqlDataAdapter da=new SqlDataAdapter();
     da.SelectCommand=cmd;
     DataSet ds=new DataSet();
     da.Fill(ds);
     cn.Close();
     this.Label1.Text=ds.Tables[0].Rows[0][1].ToString();
     this.Label2.Text=ds.Tables[0].Rows[0][2].ToString();
     this.Label4.Text=ds.Tables[0].Rows[0][3].ToString();
     this.Panel2.Controls.Add(new LiteralControl(ds.Tables[0].Rows[0][4].ToString()));
    }
   }
  }

  #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
 }
}


//购物车页面。实现此功能主要使用DataGrid来显示总计功能。

<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="CartTest.WebForm1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
 <HEAD>
  <title>WebForm1</title>
  <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
  <meta name="CODE_LANGUAGE" Content="C#">
  <meta name="vs_defaultClientScript" content="JavaScript">
  <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
  <script>
//此JS主要是防止用户输入非数字
   function checkNum()
   {
    var chr=String.fromCharCode(event.keyCode);
    
    if(isNaN(chr))
    {
    event.keyCode=0;
    }
   }
   
  </script>
 </HEAD>
 <body MS_POSITIONING="GridLayout">
  <form id="Form1" method="post" runat="server">
   <asp:DataGrid id="DataGrid1" runat="server" AutoGenerateColumns="False" PageSize="15" Font-Size="XX-Small"
    CellPadding="4" DataKeyField="BookID" BorderStyle="Solid" BorderColor="SkyBlue" BorderWidth="1px"
    ShowFooter="True" Width="680px">
    <ItemStyle BackColor="#EEEEEE"></ItemStyle>
    <HeaderStyle Font-Size="9pt" Font-Bold="True" BackColor="SkyBlue"></HeaderStyle>
    <Columns>
     <asp:TemplateColumn HeaderText="书名">
      <ItemTemplate>
       <asp:Label id=Label2 runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.Title") %>'>
       </asp:Label>
      </ItemTemplate>
     </asp:TemplateColumn>
     <asp:TemplateColumn HeaderText="单价">
      <ItemTemplate>
       <asp:TextBox id=txtPrice runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.Price") %>' ReadOnly="True">
       </asp:TextBox>
      </ItemTemplate>
     </asp:TemplateColumn>
     <asp:TemplateColumn HeaderText="数量">
      <ItemTemplate>
       <asp:TextBox id=txtNum οnkeypress="checkNum()" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.Num") %>'>
       </asp:TextBox>
      </ItemTemplate>
     </asp:TemplateColumn>
     <asp:TemplateColumn HeaderText="总金额">
      <ItemTemplate>
       <asp:TextBox id=txtSum runat="server" ReadOnly="True" Text='<%# DataBinder.Eval(Container, "DataItem.Sum") %>'>
       </asp:TextBox>
      </ItemTemplate>
      <FooterTemplate>
       <asp:TextBox id="txtSumPrice" runat="server" ReadOnly="True"></asp:TextBox>
      </FooterTemplate>
     </asp:TemplateColumn>
     <asp:TemplateColumn HeaderText="操作">
      <ItemTemplate>
       <asp:LinkButton id="LinkButton1" runat="server" CommandName="editBook">修改</asp:LinkButton><FONT face="宋体">&nbsp;</FONT>
       <asp:LinkButton id="LinkButton2" runat="server" CommandName="delBook">删除</asp:LinkButton>
      </ItemTemplate>
     </asp:TemplateColumn>
    </Columns>
    <PagerStyle NextPageText="4" Font-Size="10pt" Font-Names="webdings" PrevPageText="3" BackColor="SkyBlue"></PagerStyle>
   </asp:DataGrid>
  </form>
 </body>
</HTML>

//购物车察看页里的数据是Session里所存放的Books集合对象。可以将其绑定到网格控件

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 CartTest
{
 /// <summary>
 /// WebForm1 的摘要说明。
 /// </summary>
 public class WebForm1 : System.Web.UI.Page
 {
  protected System.Web.UI.WebControls.DataGrid DataGrid1;
  
  private void Page_Load(object sender, System.EventArgs e)
  {
   if(!this.IsPostBack)
   {
    Books bs=(Books)Session["MyCart"];
    this.DataGrid1.DataSource=bs;
    this.DataBind();
   }
  }

  #region Web 窗体设计器生成的代码
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
   //
   InitializeComponent();
   base.OnInit(e);
  }
  
  /// <summary>
  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  /// </summary>
  private void InitializeComponent()
  {   
   this.DataGrid1.ItemCreated += new System.Web.UI.WebControls.DataGridItemEventHandler(this.DataGrid1_ItemCreated);
   this.DataGrid1.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGrid1_ItemCommand);
   this.DataGrid1.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.DataGrid1_ItemDataBound);
   this.Load += new System.EventHandler(this.Page_Load);

  }
  #endregion

 

  //利用此事件对网格控件的外观进行控件(合并列)
  private void DataGrid1_ItemCreated(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
  {
   ListItemType itemType = e.Item.ItemType;
   if (itemType == ListItemType.Footer)
   {
//    e.Item.BackColor = Color.SeaGreen; 
//    e.Item.Font.Bold = true;
    e.Item.Cells.RemoveAt(0); 
    e.Item.Cells.RemoveAt(0);
    e.Item.Cells[0].ColumnSpan = 3;  
    e.Item.Cells[0].HorizontalAlign = HorizontalAlign.Right;
    
   }     
  }

 
  private void DataGrid1_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
  {
   Books bs=(Books)Session["MyCart"];
   if(e.CommandName=="editBook")
   {
     int num=Convert.ToInt16(((TextBox)e.Item.FindControl("txtNum")).Text);
     decimal p=Convert.ToDecimal(((TextBox)e.Item.FindControl("txtPrice")).Text);
     bs[this.DataGrid1.DataKeys[e.Item.ItemIndex].ToString()].Sum=p*num;
    bs[this.DataGrid1.DataKeys[e.Item.ItemIndex].ToString()].Num=num;
   }
   else if(e.CommandName=="delBook")
   {
    bs.Remove(this.DataGrid1.DataKeys[e.Item.ItemIndex].ToString());
   }
   this.DataGrid1.DataSource=bs;
   this.DataBind();
   Session["MyCart"]=bs;
  }

  private void DataGrid1_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
  {
   ListItemType itemType = e.Item.ItemType;
   if (itemType == ListItemType.Footer)
   {
    decimal sum=0;
    foreach(DataGridItem item in this.DataGrid1.Items)
    {
     decimal p=Convert.ToDecimal(((TextBox) item.FindControl("txtPrice")).Text);
     int n=Convert.ToInt16(((TextBox) item.FindControl("txtNum")).Text);
     sum+=p*n;
    }
    ((TextBox)e.Item.FindControl("txtSumPrice")).Text=sum.ToString();
   
    
    
   }     
  }
 }
}


此外我们还要在Global.asax.CS文件中将变量进行初始化,确保每个客户端访问网站时都有一个购物车,当然里面是没有书的。

此购物车实现的原理很简单.首先自己定义一个货物类,及货物集合类(实现IEnumerable集合).当每个用户进入到网站时,首先给其分配一个空的购物车。当用户在购物页面选取一个货物时,取得该货物,同时获得自己的购物车,将货物保存到购物车中,最后再保存购物车。如果用户要对购物车中的内容进行修改也是一样的原理。而且在购物车察看页。我们则将自己生成的集合类对象绑定到我们的页面中。利用网格窗控年的一此事件来处理货物统计的问题。

希望这样一个思路能对您有所帮助。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
特别说明请注意: 根许多网友反应, using Maticsoft.Functions; 这些代码看不懂 其实Functions 这个dll是我定义常用的函数类,如果需要跟我联系索取http://sql8.net 下面有我的群号, 其中 ArtsShop.Model.Arts_Product _p = new ArtsShop.Model.Arts_Product(); ArtsShop.BLL.Arts_Product p = new ArtsShop.BLL.Arts_Product(); _p = p.GetModel(id); 这是我的商品信息的类,三层结构,这个在用时你们只能换成你们自己的,这些代码完全可以删除, 比如 MyDr[1] = _p.Title; 用来读取商品名的,你们可以改MyDr[1] = dr["productname"].ToString();就行了, AddToCart.aspx页面代码 无标题页 <asp:TextBox ID="TextBox1" runat="server" Text='' Width="44px"> <asp:Label ID="Label1" runat="server" Text=''> 保存 取消 编辑 继续购物 清空购物车 下订单 AddToCart.aspx.cs页面代码 using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using Maticsoft.Functions;public partial class AddToCart : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { int ProID; HttpCookie cookie; bool Tempbl = false; string Tempstr; if (!Page.IsPostBack) { if (!object.Equals(Request.QueryString["id"], null)) { ProID = int.Parse(Request.QueryString["id"]); //创购物车cookie yxy .//sql8.net if (object.Equals(Request.Cookies["ztbscart"], null)) cookie = new HttpCookie("ztbscart"); else cookie = Request.Cookies["ztbscart"]; //判断是否已存在于购物车内 yxy // sql8.net for (int i = 0; i < cookie.Values.Keys.Count; i++) { if (!object.Equals(cookie.Values.Keys[i], null)) { Tempstr = cookie.Values.AllKeys[i].ToString(); if (Tempstr.Trim() != "") { if (ProID == int.Parse(cookie.Values.AllKeys[i])) { Tempbl = true; break; } } } } //不未购买过则加入购物车 yxy //sql8.net if (!Tempbl) cookie.Values.Add(ProID.ToString(), "1"); else { } TimeSpan ts = new TimeSpan(0, 0, 10, 0); cookie.Expires = DateTime.Now + ts; Response.AppendCookie(cookie); } BindGrid(); } } //绑定数据 yxy //sql8.net private void BindGrid() { DataTable MyDt; DataRow MyDr; string str = ""; MyDt = new DataTable(); MyDt.Columns.Add(new DataColumn("id", str.GetType())); MyDt.Columns.Add(new DataColumn("Title", str.GetType())); MyDt.Columns.Add(new DataColumn("Num", str.GetType())); MyDt.Columns.Add(new DataColumn("Price", str.GetType())); MyDt.Columns.Add(new DataColumn("Discount", str.GetType())); MyDt.Columns.Add(new DataColumn("Vipprice", str.GetType())); MyDt.Columns.Add(new DataColumn("Totle", str.GetType())); if (!object.Equals(Request.Cookies["ztbscart"], null)) { HttpCookie cookie = Request.Cookies["ztbscart"]; double Totle; //Response.Write("|" + Request.Cookies["ztbscart"].Values.Keys[1].ToString() + "|"); //Response.End(); for (int i = 0; i < cookie.Values.Keys.Count; i++) { int id; MyDr = MyDt.NewRow(); if (cookie.Values.AllKeys[i] != "" && cookie.Values[i] != "") { id = int.Parse(cookie.Values.AllKeys[i].ToString()); ArtsShop.Model.Arts_Product _p = new ArtsShop.Model.Arts_Product(); ArtsShop.BLL.Arts_Product p = new ArtsShop.BLL.Arts_Product(); _p = p.GetModel(id); MyDr[0] = id; MyDr[1] = _p.Title; MyDr[2] = cookie.Values[i]; MyDr[3] = _p.Price; MyDr[4] = _p.Discount; MyDr[5] = _p.Vipprice1; Totle = double.Parse(MyDr[2].ToString()) * double.Parse(MyDr[5].ToString()); MyDr[6] = Totle; MyDt.Rows.Add(MyDr); } } GridView1.DataSource = MyDt.DefaultView; GridView1.DataBind(); } } protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) { //编辑某行数量 yxy //sql8.net GridView1.EditIndex = e.NewEditIndex; BindGrid(); } protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { //取消更新 yxy //sql8.net GridView1.EditIndex = -1; BindGrid(); } protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) { //更新数量 yxy //sql8.net string num; TextBox tempbx = new TextBox(); Label templb = new Label(); tempbx = (TextBox)(GridView1.Rows[e.RowIndex].Cells[6]).Controls[1]; num = tempbx.Text.ToString(); HttpCookie cookie = new HttpCookie("ztbscart"); for (int i = 0; i < GridView1.Rows.Count; i++) { string id; string tempnum; id = GridView1.Rows[i].Cells[1].Text.ToString(); if (e.RowIndex == i) tempnum = num; else { templb = (Label)(GridView1.Rows[i].Cells[6]).Controls[1]; tempnum = templb.Text.ToString(); } if (tempnum.Trim() == "") tempnum = "0"; //Response.Write("ID:"+id.ToString() + "Num:"+tempnum+":"+i+"");//测试用途 yxy//sql8.net cookie.Values.Add(id, tempnum); } //Response.End(); TimeSpan ts = new TimeSpan(0, 0, 10, 0); cookie.Expires = DateTime.Now + ts; Response.AppendCookie(cookie); GridView1.EditIndex = -1; Message.GoTo("AddToCart.aspx"); } protected void LinkButton4_Click(object sender, EventArgs e) { //继续购物 yxy //sql8.net Message.WebClose(); } protected void LinkButton3_Click(object sender, EventArgs e) { //清空购物车 yxy //sql8.net CheckBox tempcb = new CheckBox(); HttpCookie cookie = new HttpCookie("ztbscart"); Label templb = new Label(); for (int i = 0; i < GridView1.Rows.Count; i++) { tempcb = (CheckBox)(GridView1.Rows[i].Cells[0]).Controls[1]; if (!tempcb.Checked) { string id; string tempnum; id = GridView1.Rows[i].Cells[1].Text.ToString(); templb = (Label)(GridView1.Rows[i].Cells[6]).Controls[1]; tempnum = templb.Text.ToString(); if (tempnum.Trim() == "") tempnum = "0"; //Response.Write("ID:"+id.ToString() + "Num:"+tempnum+":"+i+"");//测试用途 yxy//sql8.net cookie.Values.Add(id, tempnum); } } TimeSpan ts = new TimeSpan(0, 0, 10, 0); cookie.Expires = DateTime.Now + ts; Response.AppendCookie(cookie); Message.GoTo("AddToCart.aspx"); } protected void CheckAll_CheckedChanged(object sender, EventArgs e) { //全选事件 yxy //sql8.net CheckBox tempcb = new CheckBox(); bool tempbl; tempcb = (CheckBox)(GridView1.HeaderRow.Cells[0]).Controls[1]; tempbl = tempcb.Checked; for (int i = 0; i < GridView1.Rows.Count; i++) { tempcb = (CheckBox)(GridView1.Rows[i].Cells[0]).Controls[1]; tempcb.Checked = tempbl; } } } _________________________________________________________________________ 如转载请注明原出处 www.sql8.net

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值