熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> .NET編程 >> 正文

購物車的C#實現及結算處理

2013-11-13 09:54:26  來源: .NET編程 

  本示例利用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=m;
  //一種書的總金額
  public decimal Sum
  {
   get{return sum;}
   set{sum=value;}
  }
 }

  }

  //購物車集合
//Books 用戶所有訂購的書 實現IEnumerable接口我們可以將其綁定到datagrid控件
using System;
using SystemCollections;
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(htContainsKey(bBookID))
   {
 ((Book)ht[bBookID])Num=((Book)ht[bBookID])Num+bNum;
    
   }
   else
   {
    htAdd(bBookIDb);
   }
  }

  public void Remove(string bookid)
  {
   if(htContainsKey(bookid))
   htRemove(bookid);
  }
//統計有多少種書
  public int Count
  {
   get
   {
    return htCount;
   }
  }

  public void Clear()
  {
   htClear();
  }

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

  public IEnumerator GetEnumerator()
  {
   // TODO:  添加 BooksGetEnumerator 實現
   return htValuesGetEnumerator();
  }

  #endregion
 }
}

  //此頁面主要是用於顯示所有的書用的是DataList來自定義顯示模板但是實際上可以使用DataGrid來處理DataGrid也可以實現分頁功能及自定義模板只要將dDatagrid設為一個模板列然後將DataList裡的模板列代碼Copy過去即可
//此頁面中每本書都要顯示封面這個問題我們可以通過一個過渡頁來處理圖片數據

  <%@ Page language=c# Codebehind=BookListaspxcs AutoEventWireup=false Inherits=CartTestBookList %>
<!DOCTYPE HTML PUBLIC //WC//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 <%# BookViewaspx?BookID=+DataBinderEval(Container DataItemBookGuid) %>>
  <!imageviewaspx頁面專用來處理書的圖片>    <asp:Image id=Image runat=server Width=px Height=px ImageUrl=<%# ImageViewaspx?imgid=+DataBinderEval(Container DataItemBookGuid) %>>
         </asp:Image>
        </a>
       </TD>
       <TD vAlign=top>
        <TABLE id=Table cellSpacing= cellPadding= width= border=>
         <TR>
          <TD>書名
           <asp:Label id=Label runat=server Text=<%# DataBinderEval(Container DataItemBookTitle) %>>
           </asp:Label></TD>
         </TR>
         <TR>
          <TD>圖書簡介
           <asp:Label id=Label runat=server Width= Text=<%# <nobr>+DataBinderEval(Container DataItemBookComment)+/<nobr>%> Height=px>
           </asp:Label></TD>
         </TR>
         <TR>
          <TD>金額
           <asp:Label id=Label runat=server Text=<%# DataBinderEval(Container DataItemPrice{: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=<%# DataBinderEval(Container DataItemPublishDate {:D}) %>>
        </asp:Label></TD>
       <TD align=right>
        <asp:ImageButton id=Imagebutton runat=server ImageUrl=agif CommandName=AddCart></asp:ImageButton></TD>
      </TR>
     </TABLE>
    </ItemTemplate>
    <AlternatingItemTemplate>
     <TABLE id=Table cellSpacing= cellPadding= bgColor=#eefeff border=>
      <TR>
       <TD>
        <a <%# BookViewaspx?BookID=+DataBinderEval(Container DataItemBookGuid) %>>
 <!imageviewaspx頁面專用來處理書的圖片>        <asp:Image id=Image runat=server Width=px Height=px ImageUrl=<%# ImageViewaspx?imgid=+DataBinderEval(Container DataItemBookGuid) %>>
         </asp:Image></a></TD>
       <TD vAlign=top>
        <TABLE id=Table cellSpacing= cellPadding= width= border=>
         <TR>
          <TD>書名
           <asp:Label id=Label runat=server Text=<%# DataBinderEval(Container DataItemBookTitle) %>>
           </asp:Label></TD>
         </TR>
         <TR>
          <TD>圖書簡介
           <asp:Label id=Label runat=server Width=px Text=<%# DataBinderEval(Container DataItemBookComment) %> Height=px>
           </asp:Label></TD>
         </TR>
         <TR>
          <TD>金額
           <asp:Label id=Label runat=server Text=<%# DataBinderEval(Container DataItemPrice) %>>
           </asp:Label></TD>
         </TR>
        </TABLE>
       </TD>
      </TR>
      <TR>
       <TD>
        <asp:Label id=Label runat=server>日期</asp:Label>
        <asp:Label id=Label runat=server Text=<%# DataBinderEval(Container DataItemPublishDate) %>>
        </asp:Label></TD>
       <TD align=right>
        <asp:ImageButton id=Imagebutton runat=server ImageUrl=agif></asp:ImageButton></TD>
      </TR>
     </TABLE>
    </AlternatingItemTemplate>
   </asp:datalist></form>
 </body>
</HTML>

  //CS CODE
using System;
using SystemCollections;
using SystemComponentModel;
using SystemData;
using SystemDrawing;
using SystemWeb;
using SystemWebSessionState;
using SystemWebUI;
using SystemWebUIWebControls;
using SystemWebUIHtmlControls;
using SystemDataSqlClient;
namespace CartTest
{
 /// <summary>
 /// BookList 的摘要說明
 /// </summary>
 public class BookList : SystemWebUIPage
 {
  protected SystemWebUIWebControlsDataList DataList;
 
  private void Page_Load(object sender SystemEventArgs e)
  {
   if(!thisIsPostBack)
   {
    SqlConnection cn=new SqlConnection();
    cnConnectionString=server=;uid=sa;pwd=;database=p;
    cnOpen();
    SqlCommand cmd=new SqlCommand();
    cmdConnection=cn;
    cmdCommandText=select * from books ;
    SqlDataAdapter da=new SqlDataAdapter();
    daSelectCommand=cmd;
    DataSet ds=new DataSet();
    daFill(ds);
    cnClose();
    thisDataListDataSource=dsTables[];
    thisDataBind();
   }
  }

  #region Web 窗體設計器生成的代碼
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN: 該調用是 ASPNET Web 窗體設計器所必需的
   //
   InitializeComponent();
   baseOnInit(e);
  }
  
  /// <summary>
  /// 設計器支持所需的方法 不要使用代碼編輯器修改
  /// 此方法的內容
  /// </summary>
  private void InitializeComponent()
  {   
   thisDataListItemCommand += new SystemWebUIWebControlsDataListCommandEventHandler(thisDataList_ItemCommand);
   thisLoad += new SystemEventHandler(thisPage_Load);

  }
  #endregion

  private void DataList_ItemCommand(object source SystemWebUIWebControlsDataListCommandEventArgs e)
  {
  
   //用戶選中一本書後默認訂一本書
   string bookGuid=thisDataListDataKeys[eItemItemIndex]ToString();
   Book b=new Book();
   //首先獲得自己的購物車
   Books bs=(Books)Session[MyCart];
   bBookID=bookGuid;
   bNum=;
   //根據ITEM的類型取值
   if(eItemItemType==ListItemTypeItem)
   {
    bPrice=ConvertToDecimal(((Label)eItemFindControl(Label))TextSubstring());
    bTitle=((Label)eItemFindControl(Label))Text;
   }
   else if(eItemItemType==ListItemTypeAlternatingItem)
   {
    bPrice=ConvertToDecimal(((Label)eItemFindControl(Label))TextSubstring());
    bTitle=((Label)eItemFindControl(Label))Text;
   }
   //將書加入到購物車
   bsAdd(b);
   Session[MyCart]=bs;
   //打開購物車頁面
   ResponseWrite(<script>windowopen(webformaspx)</script>);
  }

  }
}

  //圖片處理頁
using System;
using SystemCollections;
using SystemComponentModel;
using SystemData;
using SystemDrawing;
using SystemWeb;
using SystemWebSessionState;
using SystemWebUI;
using SystemWebUIWebControls;
using SystemWebUIHtmlControls;
using SystemDataSqlClient;
namespace CartTest
{
 /// <summary>
 /// ImageView 的摘要說明
 /// </summary>
 public class ImageView : SystemWebUIPage
 {
 
  private void Page_Load(object sender SystemEventArgs e)
  {
   SqlConnection cn=new SqlConnection();
   cnConnectionString=server=;uid=sa;pwd=;database=p;
   cnOpen();
   SqlCommand cmd=new SqlCommand();
   cmdConnection=cn;
   cmdCommandText=select cover from books where bookguid=+ thisRequestQueryString[imgid]ToString() +;
   //cmdCommandText=select cover from books where bookguid=bcadcbeeee;
   SqlDataAdapter da=new SqlDataAdapter();
   daSelectCommand=cmd;
   DataSet ds=new DataSet();
   daFill(ds);
   cnClose();
   ResponseClear();
   ResponseClearContent();
   ResponseContentType=Image/jpg;
   ResponseBinaryWrite((byte[])dsTables[]Rows[][]);

  }

  #region Web 窗體設計器生成的代碼
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN: 該調用是 ASPNET Web 窗體設計器所必需的
   //
   InitializeComponent();
   baseOnInit(e);
  }
  
  /// <summary>
  /// 設計器支持所需的方法 不要使用代碼編輯器修改
  /// 此方法的內容
  /// </summary>
  private void InitializeComponent()
  {   
   thisLoad += new SystemEventHandler(thisPage_Load);

  }
  #endregion
 }
}

  //當用戶選取其中一本書時獲得用戶當前選中書的ID將此ID傳到具體察看頁面
<%@ Page language=c# Codebehind=BookViewaspxcs AutoEventWireup=false Inherits=CartTestBookView %>
<!DOCTYPE HTML PUBLIC //WC//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 SystemCollections;
using SystemComponentModel;
using SystemData;
using SystemDrawing;
using SystemWeb;
using SystemWebSessionState;
using SystemWebUI;
using SystemWebUIWebControls;
using SystemWebUIHtmlControls;
using SystemDataSqlClient;

  namespace CartTest
{
 /// <summary>
 /// BookView 的摘要說明
 /// </summary>
 public class BookView : SystemWebUIPage
 {
  protected SystemWebUIWebControlsLabel Label;
  protected SystemWebUIWebControlsImage Image;
  protected SystemWebUIWebControlsLabel Label;
  protected SystemWebUIWebControlsLabel Label;
  protected SystemWebUIWebControlsTextBox TextBox;
  protected SystemWebUIWebControlsLabel Label;
  protected SystemWebUIWebControlsPanel Panel;
  protected SystemWebUIWebControlsLabel Label;
  protected SystemWebUIWebControlsPanel Panel;
 
  private void Page_Load(object sender SystemEventArgs e)
  {
   if(!thisIsPostBack)
   {
    if(thisRequest[BookID]!=null)
    {
     thisImageImageUrl=ImageViewaspx?imgid=+thisRequest[BookID]ToString();
     SqlConnection cn=new SqlConnection();
     cnConnectionString=server=;uid=sa;pwd=;database=p;
     cnOpen();
     SqlCommand cmd=new SqlCommand();
     cmdConnection=cn;
     cmdCommandText=select * from books where bookguid=+ thisRequestQueryString[BookID]ToString() +;
     //cmdCommandText=select cover from books where bookguid=bcadcbeeee;
     SqlDataAdapter da=new SqlDataAdapter();
     daSelectCommand=cmd;
     DataSet ds=new DataSet();
     daFill(ds);
     cnClose();
     thisLabelText=dsTables[]Rows[][]ToString();
     thisLabelText=dsTables[]Rows[][]ToString();
     thisLabelText=dsTables[]Rows[][]ToString();
     thisPanelControlsAdd(new LiteralControl(dsTables[]Rows[][]ToString()));
    }
   }
  }

  #region Web 窗體設計器生成的代碼
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN: 該調用是 ASPNET Web 窗體設計器所必需的
   //
   InitializeComponent();
   baseOnInit(e);
  }
  
  /// <summary>
  /// 設計器支持所需的方法 不要使用代碼編輯器修改
  /// 此方法的內容
  /// </summary>
  private void InitializeComponent()
  {   
   thisLoad += new SystemEventHandler(thisPage_Load);

  }
  #endregion
 }
}

  //購物車頁面實現此功能主要使用DataGrid來顯示總計功能

  <%@ Page language=c# Codebehind=WebFormaspxcs AutoEventWireup=false Inherits=CartTestWebForm %>
<!DOCTYPE HTML PUBLIC //WC//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=StringfromCharCode(eventkeyCode);
    
    if(isNaN(chr))
    {
    eventkeyCode=;
    }
   }
   
  </script>
 </HEAD>
 <body MS_POSITIONING=GridLayout>
  <form id=Form method=post runat=server>
   <asp:DataGrid id=DataGrid runat=server AutoGenerateColumns=False PageSize= FontSize=XXSmall
    CellPadding= DataKeyField=BookID BorderStyle=Solid BorderColor=SkyBlue BorderWidth=px
    ShowFooter=True Width=px>
    <ItemStyle BackColor=#EEEEEE></ItemStyle>
    <HeaderStyle FontSize=pt FontBold=True BackColor=SkyBlue></HeaderStyle>
    <Columns>
     <asp:TemplateColumn HeaderText=書名>
      <ItemTemplate>
       <asp:Label id=Label runat=server Text=<%# DataBinderEval(Container DataItemTitle) %>>
       </asp:Label>
      </ItemTemplate>
     </asp:TemplateColumn>
     <asp:TemplateColumn HeaderText=單價>
      <ItemTemplate>
       <asp:TextBox id=txtPrice runat=server Text=<%# DataBinderEval(Container DataItemPrice) %> ReadOnly=True>
       </asp:TextBox>
      </ItemTemplate>
     </asp:TemplateColumn>
     <asp:TemplateColumn HeaderText=數量>
      <ItemTemplate>
       <asp:TextBox id=txtNum onkeypress=checkNum() runat=server Text=<%# DataBinderEval(Container DataItemNum) %>>
       </asp:TextBox>
      </ItemTemplate>
     </asp:TemplateColumn>
     <asp:TemplateColumn HeaderText=總金額>
      <ItemTemplate>
       <asp:TextBox id=txtSum runat=server ReadOnly=True Text=<%# DataBinderEval(Container DataItemSum) %>>
       </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= FontSize=pt FontNames=webdings PrevPageText= BackColor=SkyBlue></PagerStyle>
   </asp:DataGrid>
  </form>
 </body>
</HTML>

  //購物車察看頁裡的數據是Session裡所存放的Books集合對象可以將其綁定到網格控件

  using System;
using SystemCollections;
using SystemComponentModel;
using SystemData;
using SystemDrawing;
using SystemWeb;
using SystemWebSessionState;
using SystemWebUI;
using SystemWebUIWebControls;
using SystemWebUIHtmlControls;
using SystemDataSqlClient;
namespace CartTest
{
 /// <summary>
 /// WebForm 的摘要說明
 /// </summary>
 public class WebForm : SystemWebUIPage
 {
  protected SystemWebUIWebControlsDataGrid DataGrid;
  
  private void Page_Load(object sender SystemEventArgs e)
  {
   if(!thisIsPostBack)
   {
    Books bs=(Books)Session[MyCart];
    thisDataGridDataSource=bs;
    thisDataBind();
   }
  }

  #region Web 窗體設計器生成的代碼
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN: 該調用是 ASPNET Web 窗體設計器所必需的
   //
   InitializeComponent();
   baseOnInit(e);
  }
  
  /// <summary>
  /// 設計器支持所需的方法 不要使用代碼編輯器修改
  /// 此方法的內容
  /// </summary>
  private void InitializeComponent()
  {   
   thisDataGridItemCreated += new SystemWebUIWebControlsDataGridItemEventHandler(thisDataGrid_ItemCreated);
   thisDataGridItemCommand += new SystemWebUIWebControlsDataGridCommandEventHandler(thisDataGrid_ItemCommand);
   thisDataGridItemDataBound += new SystemWebUIWebControlsDataGridItemEventHandler(thisDataGrid_ItemDataBound);
   thisLoad += new SystemEventHandler(thisPage_Load);

  }
  #endregion

  //利用此事件對網格控件的外觀進行控件(合並列)
  private void DataGrid_ItemCreated(object sender SystemWebUIWebControlsDataGridItemEventArgs e)
  {
   ListItemType itemType = eItemItemType;
   if (itemType == ListItemTypeFooter)
   {
//    eItemBackColor = ColorSeaGreen; 
//    eItemFontBold = true;
    eItemCellsRemoveAt(); 
    eItemCellsRemoveAt();
    eItemCells[]ColumnSpan = ;  
    eItemCells[]HorizontalAlign = HorizontalAlignRight;
    
   }     
  }

  private void DataGrid_ItemCommand(object source SystemWebUIWebControlsDataGridCommandEventArgs e)
  {
   Books bs=(Books)Session[MyCart];
   if(eCommandName==editBook)
   {
     int num=ConvertToInt(((TextBox)eItemFindControl(txtNum))Text);
     decimal p=ConvertToDecimal(((TextBox)eItemFindControl(txtPrice))Text);
     bs[thisDataGridDataKeys[eItemItemIndex]ToString()]Sum=p*num;
    bs[thisDataGridDataKeys[eItemItemIndex]ToString()]Num=num;
   }
   else if(eCommandName==delBook)
   {
    bsRemove(thisDataGridDataKeys[eItemItemIndex]ToString());
   }
   thisDataGridDataSource=bs;
   thisDataBind();
   Session[MyCart]=bs;
  }

  private void DataGrid_ItemDataBound(object sender SystemWebUIWebControlsDataGridItemEventArgs e)
  {
   ListItemType itemType = eItemItemType;
   if (itemType == ListItemTypeFooter)
   {
    decimal sum=;
    foreach(DataGridItem item in thisDataGridItems)
    {
     decimal p=ConvertToDecimal(((TextBox) itemFindControl(txtPrice))Text);
     int n=ConvertToInt(((TextBox) itemFindControl(txtNum))Text);
     sum+=p*n;
    }
    ((TextBox)eItemFindControl(txtSumPrice))Text=sumToString();
   
    
    
   }     
  }
 }
}

  此外我們還要在GlobalasaxCS文件中將變量進行初始化確保每個客戶端訪問網站時都有一個購物車當然裡面是沒有書的

  此購物車實現的原理很簡單首先自己定義一個貨物類及貨物集合類(實現IEnumerable集合)當每個用戶進入到網站時首先給其分配一個空的購物車當用戶在購物頁面選取一個貨物時取得該貨物同時獲得自己的購物車將貨物保存到購物車中最後再保存購物車如果用戶要對購物車中的內容進行修改也是一樣的原理而且在購物車察看頁我們則將自己生成的集合類對象綁定到我們的頁面中利用網格窗控年的一此事件來處理貨物統計的問題


From:http://tw.wingwit.com/Article/program/net/201311/11934.html
    推薦文章
    Copyright © 2005-2013 電腦知識網 Computer Knowledge   All rights reserved.