本示例利用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 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="LinkButton1" runat="server" CommandName="editBook">修改</asp:LinkButton><FONT face="宋体"> </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集合).当每个用户进入到网站时,首先给其分配一个空的购物车。当用户在购物页面选取一个货物时,取得该货物,同时获得自己的购物车,将货物保存到购物车中,最后再保存购物车。如果用户要对购物车中的内容进行修改也是一样的原理。而且在购物车察看页。我们则将自己生成的集合类对象绑定到我们的页面中。利用网格窗控年的一此事件来处理货物统计的问题。
希望这样一个思路能对您有所帮助。
本文地址:http://com.8s8s.com/it/it42684.htm