知识大全 购物车的C#实现及结算处理

Posted

篇首语:将相本无种,男儿当自强。本文由小常识网(cha138.com)小编为大家整理,主要介绍了知识大全 购物车的C#实现及结算处理相关的知识,希望对你有一定的参考价值。

购物车的C#实现及结算处理  以下文字资料是由(全榜网网www.cha138.com)小编为大家搜集整理后发布的内容,让我们赶快一起来看一下吧!

  本示例利用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     getreturn bookid;   setbookid=value;    /// <summary>  /// 书名  /// </summary>  public string Title     getreturn title;   settitle=value;      /// <summary>  /// 金额  /// </summary>  public decimal Price     getreturn price;   setprice=value;   sum=price*num;       /// <summary>  /// 数量  /// </summary>  public int Num     getreturn num;   setnum=value;   sum=price*num;       decimal sum= m;  //一种书的总金额  public decimal Sum     getreturn sum;   setsum=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 //W C//DTD HTML Transitional//EN ><HTML> <HEAD>  <title>BookList</title>  <meta content= Microsoft Visual Studio NET name= GENERATOR >  <meta content= C# name= CODE_LANGUAGE >  <meta content= javascript name= vs_defaultClientScript >  <meta content= name= vs_targetSchema >  <LINK text/css rel= stylesheet > </HEAD> <body MS_POSITIONING= GridLayout >  <form id= Form method= post runat= server >   <asp:datalist id= DataList runat= server     DataKeyField= BookGuid Width= >    <ItemTemplate>     <TABLE id= Table cellSpacing= cellPadding= border= >      <TR>       <TD>        <a <%# BookView aspx?BookID= +DataBinder Eval(Container DataItem BookGuid ) %> >  <! imageview aspx页面专用来处理书的图片 >    <asp:Image id=Image runat= server Width= px Height= px ImageUrl= <%# ImageView aspx?imgid= +DataBinder Eval(Container DataItem BookGuid ) %> >         </asp:Image>        </a>       </TD>       <TD vAlign= top >        <TABLE id= Table cellSpacing= cellPadding= width= border= >         <TR>          <TD>书名            <asp:Label id=Label runat= server Text= <%# DataBinder Eval(Container DataItem BookTitle ) %> >           </asp:Label></TD>         </TR>         <TR>          <TD>图书简介            <asp:Label id=Label runat= server Width= Text= <%# <nobr> +DataBinder Eval(Container DataItem BookComment )+ /<nobr> %> Height= px >           </asp:Label></TD>         </TR>         <TR>          <TD>金额            <asp:Label id=Label runat= server Text= <%# DataBinder Eval(Container DataItem Price :C ) %> >           </asp:Label></TD>         </TR>        </TABLE>       </TD>      </TR>      <TR>       <TD>        <asp:Label id= Label runat= server >日期 </asp:Label>        <asp:Label id=Label runat= server Text= <%# DataBinder Eval(Container DataItem PublishDate :D ) %> >        </asp:Label></TD>       <TD align= right >        <asp:ImageButton id= Imagebutton runat= server ImageUrl= a gif CommandName= AddCart ></asp:ImageButton></TD>      </TR>     </TABLE>    </ItemTemplate>    <AlternatingItemTemplate>     <TABLE id= Table cellSpacing= cellPadding= bgColor= #eefeff border= >      <TR>       <TD>        <a <%# BookView aspx?BookID= +DataBinder Eval(Container DataItem BookGuid ) %> > <! imageview aspx页面专用来处理书的图片 >        <asp:Image id=Image runat= server Width= px Height= px ImageUrl= <%# ImageView aspx?imgid= +DataBinder Eval(Container DataItem BookGuid ) %> >         </asp:Image></a></TD>       <TD vAlign= top >        <TABLE id= Table cellSpacing= cellPadding= width= border= >         <TR>          <TD>书名            <asp:Label id=Label runat= server Text= <%# DataBinder Eval(Container DataItem BookTitle ) %> >           </asp:Label></TD>         </TR>         <TR>          <TD>图书简介            <asp:Label id=Label runat= server Width= px Text= <%# DataBinder Eval(Container DataItem BookComment ) %> Height= px >           </asp:Label></TD>         </TR>         <TR>          <TD>金额            <asp:Label id=Label runat= server Text= <%# DataBinder Eval(Container DataItem Price ) %> >           </asp:Label></TD>         </TR>        </TABLE>       </TD>      </TR>      <TR>       <TD>        <asp:Label id= Label runat= server >日期 </asp:Label>        <asp:Label id=Label runat= server Text= <%# DataBinder Eval(Container DataItem PublishDate ) %> >        </asp:Label></TD>       <TD align= right >        <asp:ImageButton id= Imagebutton runat= server ImageUrl= a gif ></asp:ImageButton></TD>      </TR>     </TABLE>    </AlternatingItemTemplate>   </asp:datalist></form> </body></HTML>

  //CS CODEusing 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 DataList ;   private void Page_Load(object sender System EventArgs e)     if(!this IsPostBack)       SqlConnection cn=new SqlConnection();    cn ConnectionString= server= ;uid=sa;pwd=;database=p ;    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 DataList DataSource=ds Tables[ ];    this DataBind();     

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

    #endregion

  private void DataList _ItemCommand(object source System Web UI WebControls DataListCommandEventArgs e)       //用户选中一本书后 默认订一本书   string bookGuid=this DataList DataKeys[e Item ItemIndex] ToString();   Book b=new Book();   //首先获得自己的购物车   Books bs=(Books)Session[ MyCart ];   b BookID=bookGuid;   b Num= ;   //根据ITEM的类型取值   if(e Item ItemType==ListItemType Item)       b Price=Convert ToDecimal(((Label)e Item FindControl( Label )) Text Substring( ));    b Title=((Label)e Item FindControl( Label )) Text;      else if(e Item ItemType==ListItemType AlternatingItem)       b Price=Convert ToDecimal(((Label)e Item FindControl( Label )) Text Substring( ));    b Title=((Label)e Item FindControl( Label )) Text;      //将书加入到购物车   bs Add(b);   Session[ MyCart ]=bs;   //打开购物车页面    Response Write( <script>window open( webform 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=p ;   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= bc a d c b e e e e ;   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[ ] Rows[ ][ ]);

  

  #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 //W C//DTD HTML Transitional//EN ><HTML>  <HEAD>  <title>BookView</title>  <meta name= GENERATOR Content= Microsoft Visual Studio NET >  <meta name= CODE_LANGUAGE Content= C# >  <meta name= vs_defaultClientScript content= javascript >  <meta name= vs_targetSchema content= >  </HEAD> <body MS_POSITIONING= GridLayout >  <form id= Form method= post runat= server >   <FONT face= 宋体 >    <asp:Label id= Label runat= server      Width= px Height= px ></asp:Label>    <asp:Image id= Image runat= server      Width= px Height= px ></asp:Image>    <asp:Label id= Label runat= server      Width= px ></asp:Label>    <asp:Label id= Label runat= server Width= px >Label</asp:Label><asp:Panel id=Panel runat= server Height= px Width= px ></asp:Panel><asp:Label id=Label runat= server Width= px >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 Label ;  protected System Web UI WebControls Image Image ;  protected System Web UI WebControls Label Label ;  protected System Web UI WebControls Label Label ;  protected System Web UI WebControls TextBox TextBox ;  protected System Web UI WebControls Label Label ;  protected System Web UI WebControls Panel Panel ;  protected System Web UI WebControls Label Label ;  protected System Web UI WebControls Panel Panel ;   private void Page_Load(object sender System EventArgs e)     if(!this IsPostBack)       if(this Request[ BookID ]!=null)         this Image ImageUrl= ImageView aspx?imgid= +this Request[ BookID ] ToString();     SqlConnection cn=new SqlConnection();     cn ConnectionString= server= ;uid=sa;pwd=;database=p ;     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= bc a d c b e e e e ;     SqlDataAdapter da=new SqlDataAdapter();     da SelectCommand=cmd;     DataSet ds=new DataSet();     da Fill(ds);     cn Close();     this Label Text=ds Tables[ ] Rows[ ][ ] ToString();     this Label Text=ds Tables[ ] Rows[ ][ ] ToString();     this Label Text=ds Tables[ ] Rows[ ][ ] ToString();     this Panel Controls Add(new LiteralControl(ds Tables[ ] Rows[ ][ ] 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= WebForm aspx cs AutoEventWireup= false Inherits= CartTest WebForm %><!DOCTYPE HTML PUBLIC //W C//DTD HTML Transitional//EN ><HTML> <HEAD>  <title>WebForm </title>  <meta name= GENERATOR Content= Microsoft Visual Studio NET >  <meta name= CODE_LANGUAGE Content= C# >  <meta name= vs_defaultClientScript content= javascript >  <meta name= vs_targetSchema content= >  <script>//此JS主要是防止用户输入非数字   function checkNum()       var chr=String fromCharCode(event keyCode);        if(isNaN(chr))        event keyCode= ;            </script> </HEAD> <body MS_POSITIONING= GridLayout >  <form id= Form method= post runat= server >   <asp:DataGrid id= DataGrid runat= server AutoGenerateColumns= False PageSize= Font Size= XX Small     CellPadding= DataKeyField= BookID BorderStyle= Solid BorderColor= SkyBlue BorderWidth= px     ShowFooter= True Width= px >    <ItemStyle BackColor= #EEEEEE ></ItemStyle>    <HeaderStyle Font Size= pt Font Bold= True BackColor= SkyBlue ></HeaderStyle>    <Columns>     <asp:TemplateColumn HeaderText= 书名 >      <ItemTemplate>       <asp:Label id=Label 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 onkeypress= 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= LinkButton runat= server CommandName= editBook >修改</asp:LinkButton><FONT face= 宋体 >&nbsp;</FONT>       <asp:LinkButton id= LinkButton runat= server CommandName= delBook >删除</asp:LinkButton>      </ItemTemplate>     </asp:TemplateColumn>    </Columns>    <PagerStyle NextPageText= Font Size= pt Font Names= webdings PrevPageText= 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> /// WebForm 的摘要说明  /// </summary> public class WebForm : System Web UI Page   protected System Web UI WebControls DataGrid DataGrid ;    private void Page_Load(object sender System EventArgs e)     if(!this IsPostBack)       Books bs=(Books)Session[ MyCart ];    this DataGrid 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 DataGrid ItemCreated += new System Web UI WebControls DataGridItemEventHandler(this DataGrid _ItemCreated);   this DataGrid ItemCommand += new System Web UI WebControls DataGridCommandEventHandler(this DataGrid _ItemCommand);   this DataGrid ItemDataBound += new System Web UI WebControls DataGridItemEventHandler(this DataGrid _ItemDataBound);   this Load += new System EventHandler(this Page_Load);

    #endregion

  //利用此事件对网格控件的外观进行控件(合并列)  private void DataGrid _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( );     e Item Cells RemoveAt( );    e Item Cells[ ] ColumnSpan = ;      e Item Cells[ ] HorizontalAlign = HorizontalAlign Right;               

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

  private void DataGrid _ItemDataBound(object sender System Web UI WebControls DataGridItemEventArgs e)     ListItemType itemType = e Item ItemType;   if (itemType == ListItemType Footer)        decimal sum= ;    foreach(DataGridItem item in this DataGrid Items)         decimal p=Convert ToDecimal(((TextBox) item FindControl( txtPrice )) Text);     int n=Convert ToInt (((TextBox) item FindControl( txtNum )) Text);     sum+=p*n;        ((TextBox)e Item FindControl( txtSumPrice )) Text=sum ToString();                       

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

cha138/Article/program/net/201311/11934

相关参考

知识大全 JSP培训之购物车实例及小结

JSP培训之购物车实例及小结  以下文字资料是由(全榜网网www.cha138.com)小编为大家搜集整理后发布的内容,让我们赶快一起来看一下吧!cha138/

.试比较债权结算帐户,债务结算帐户及债权债务结算帐户的结构特点?

债权结算账户的结构特点是,借方登记债权的增加额,贷方登记债权的减少额,期末余额一般在借方,表示期末尚未收回债,权的实有额.  债务结算账户的结构特点是,贷方登记债务的增加额,借方登记债务的减少额,期末

消费者李某在购物中心购买了一台音响设备,后经有关部门认定该音响为不合格商品,李某找到购物中心要求退货。下列处理方法中,正

消费者李某在购物中心购买了一台音响设备,后经有关部门认定该音响为不合格商品,李某找到购物中心要求退货。下列处理方法中,正确的是_____。A、该购物中心认为可以通过更换使李某得到合格产品,因而拒绝退货

江某在某超市购买了一台电动榨汁机,1个月后出现故障,要求超市处理。但超市“购物须知”规定在本超市购物有质量问题请及时解决

江某在某超市购买了一台电动榨汁机,1个月后出现故障,要求超市处理。但超市“购物须知”规定在本超市购物有质量问题请及时解决,自购物之日起超过15日的概不退换。”超市以此为由,拒绝受理,要求江某与生产厂家

企业如何申请核定限额及申请开立外汇结算帐户?

企业申请开立外汇结算帐户核定限额须到外汇局领取并填写“外汇结算帐户核定限额申请表”及“开立外汇帐户批准书”,并提供以下材料:  (1)申请保留一定限额外汇的申请书;  (2)工商行政管理部门颁发的营业

跟单信用证及跟单托收贸易结算方式的售付汇如何办理?

(1)用跟单信用证/保函方式结算的贸易进口,如需在开证时购汇,持进口合同、进口付汇核销单、开证申请书;如需在付汇时购汇,还应当提供信用证结算方式要求的有效商业单据。  (2)用跟单托收方式结算的贸易进

知识大全 C#的异常处理

C#的异常处理  以下文字资料是由(全榜网网www.cha138.com)小编为大家搜集整理后发布的内容,让我们赶快一起来看一下吧!  通用语言运行时(CLR)具有的一个

知识大全 c#中构建异常处理

  异常是程序运行中发生的错误异常处理是程序设计的一部分在c#中异常处理是通过Exception基类进行的可以创建自己的异常类但这个类必须是继承自Exception基类  异常将导致不完善或者不需要的

知识大全 C#图片处理的3种高级实用方法

C#图片处理的3种高级实用方法  以下文字资料是由(全榜网网www.cha138.com)小编为大家搜集整理后发布的内容,让我们赶快一起来看一下吧!  本文介绍C#图片处

未在本行开立结算账户的客户开立定期账户,需提供哪些开户资料?

客户需提交“开立单位银行结算账户申请书”一式二联、营业执照正本及复印件、开户单位公函、单位法人及开户经办人身份证原件及复印件、四份预留印鉴的印鉴卡。