本示例利用Session对象来实现一个简单的购物车。主要用于教学演示。
Book类
此类主是代表购物车的一本书
using System;
namespace CartTest
{
///
1<summary>
2/// Books 的摘要说明。
3/// </summary>
public class Book
{
string bookid;
string title;
decimal price;
int num;
public Book()
{
}
///
1<summary>
2/// ID
3/// </summary>
public string BookID
{
get{return bookid;}
set{bookid=value;}
}
///
1<summary>
2/// 书名
3/// </summary>
public string Title
{
get{return title;}
set{title=value;}
}
///
1<summary>
2/// 金额
3/// </summary>
public decimal Price
{
get{return price;}
set{price=value;
sum=price*num;
}
}
///
1<summary>
2/// 数量
3/// </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
{
///
1<summary>
2///
3/// </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过去即可。
//此页面中每本书都要显示封面。这个问题我们可以通过一个过渡页来处理图片数据
1@ Page language="c#" Codebehind="BookList.aspx.cs" AutoEventWireup="false" Inherits="CartTest.BookList"
1<html>
2<head>
3<title>BookList</title>
4<meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR"/>
5<meta content="C#" name="CODE_LANGUAGE"/>
6<meta content="JavaScript" name="vs_defaultClientScript"/>
7<meta content=" http://schemas.microsoft.com/intellisense/ie5 " name="vs_targetSchema"/>
8<link href=" http://localhost/CartTest/StyleSheet1.css " rel="stylesheet" type="text/css"/>
9</head>
10<body ms_positioning="GridLayout">
11<form id="Form1" method="post" runat="server">
12<asp:datalist datakeyfield="BookGuid" id="DataList1" runat="server" style="Z-INDEX: 101; LEFT: 16px; POSITION: absolute; TOP: 56px" width="650">
13<itemtemplate>
14<table border="0" cellpadding="1" cellspacing="1" id="Table14">
15<tr>
16<td>
17<a href='```
18# "BookView.aspx?BookID="+DataBinder.Eval(Container, "DataItem.BookGuid")
19```'>
20<!--imageview.aspx页面专用来处理书的图片--> <asp:image height="144px" id="Image1" imageurl='```
21# "ImageView.aspx?imgid="+DataBinder.Eval(Container, "DataItem.BookGuid")
22```' runat="server" width="120px">
23</asp:image>
24</a>
25</td>
26<td valign="top">
27<table border="1" cellpadding="1" cellspacing="1" id="Table15" width="300">
28<tr>
29<td>书名:
30<asp:label id="Label1" runat="server" text='```
31# DataBinder.Eval(Container, "DataItem.BookTitle")
32```'>
33</asp:label></td>
34</tr>
35<tr>
36<td>图书简介:
37<asp:label height="50px" id="Label2" runat="server" style="OVERFLOW: hidden; TEXT-OVERFLOW: ellipsis" text='```
38# "&lt;nobr&gt;"+DataBinder.Eval(Container, "DataItem.BookComment")+"/&lt;nobr&gt;"
39```' width="496">
40</asp:label></td>
41</tr>
42<tr>
43<td>金额:
44<asp:label id="Label3" runat="server" text='```
45# DataBinder.Eval(Container, "DataItem.Price","{0:C}")
46```'>
47</asp:label></td>
48</tr>
49</table>
50</td>
51</tr>
52<tr>
53<td>
54<asp:label id="Label4" runat="server">日期:</asp:label>
55<asp:label id="Label5" runat="server" text='```
56# DataBinder.Eval(Container, "DataItem.PublishDate", "{0:D}")
57```'>
58</asp:label></td>
59<td align="right">
60<asp:imagebutton commandname="AddCart" id="Imagebutton1" imageurl="a.gif" runat="server"></asp:imagebutton></td>
61</tr>
62</table>
63</itemtemplate>
64<alternatingitemtemplate>
65<table bgcolor="#eefeff" border="0" cellpadding="1" cellspacing="1" id="Table4">
66<tr>
67<td>
68<a href='```
69# "BookView.aspx?BookID="+DataBinder.Eval(Container, "DataItem.BookGuid")
70```'>
71<!--imageview.aspx页面专用来处理书的图片--> <asp:image height="144px" id="Image2" imageurl='```
72# "ImageView.aspx?imgid="+DataBinder.Eval(Container, "DataItem.BookGuid")
73```' runat="server" width="120px">
74</asp:image></a></td>
75<td valign="top">
76<table border="1" cellpadding="1" cellspacing="1" id="Table5" width="300">
77<tr>
78<td>书名:
79<asp:label id="Label6" runat="server" text='```
80# DataBinder.Eval(Container, "DataItem.BookTitle")
81```'>
82</asp:label></td>
83</tr>
84<tr>
85<td>图书简介:
86<asp:label height="50px" id="Label7" runat="server" style="OVERFLOW: hidden; TEXT-OVERFLOW: ellipsis" text='```
87# DataBinder.Eval(Container, "DataItem.BookComment")
88```' width="496px">
89</asp:label></td>
90</tr>
91<tr>
92<td>金额:
93<asp:label id="Label8" runat="server" text='```
94# DataBinder.Eval(Container, "DataItem.Price")
95```'>
96</asp:label></td>
97</tr>
98</table>
99</td>
100</tr>
101<tr>
102<td>
103<asp:label id="Label9" runat="server">日期:</asp:label>
104<asp:label id="Label10" runat="server" text='```
105# DataBinder.Eval(Container, "DataItem.PublishDate")
106```'>
107</asp:label></td>
108<td align="right">
109<asp:imagebutton id="Imagebutton2" imageurl="a.gif" runat="server"></asp:imagebutton></td>
110</tr>
111</table>
112</alternatingitemtemplate>
113</asp:datalist></form>
114</body>
115</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
{
///
1<summary>
2/// BookList 的摘要说明。
3/// </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);
}
///
1<summary>
2/// 设计器支持所需的方法 - 不要使用代码编辑器修改
3/// 此方法的内容。
4/// </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("
1<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
{
///
1<summary>
2/// ImageView 的摘要说明。
3/// </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);
}
///
1<summary>
2/// 设计器支持所需的方法 - 不要使用代码编辑器修改
3/// 此方法的内容。
4/// </summary>
private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
}
}
//当用户选取其中一本书时,获得用户当前选中书的ID,将此ID传到具体察看页面
1@ Page language="c#" Codebehind="BookView.aspx.cs" AutoEventWireup="false" Inherits="CartTest.BookView"
1<html>
2<head>
3<title>BookView</title>
4<meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR"/>
5<meta content="C#" name="CODE_LANGUAGE"/>
6<meta content="JavaScript" name="vs_defaultClientScript"/>
7<meta content=" http://schemas.microsoft.com/intellisense/ie5 " name="vs_targetSchema"/>
8</head>
9<body ms_positioning="GridLayout">
10<form id="Form1" method="post" runat="server">
11<font face="宋体">
12<asp:label height="35px" id="Label1" runat="server" style="Z-INDEX: 101; LEFT: 32px; POSITION: absolute; TOP: 24px" width="302px"></asp:label>
13<asp:image height="136px" id="Image1" runat="server" style="Z-INDEX: 102; LEFT: 24px; POSITION: absolute; TOP: 72px" width="120px"></asp:image>
14<asp:label id="Label2" runat="server" style="Z-INDEX: 103; LEFT: 192px; POSITION: absolute; TOP: 88px" width="280px"></asp:label>
15<asp:label id="Label4" runat="server" style="Z-INDEX: 104; LEFT: 200px; POSITION: absolute; TOP: 128px" width="328px">Label</asp:label>
16<asp:panel height="172px" id="Panel2" runat="server" style="Z-INDEX: 105; LEFT: 24px; POSITION: absolute; TOP: 220px" width="456px"></asp:panel>
17<asp:label id="Label5" runat="server" style="Z-INDEX: 106; LEFT: 200px; POSITION: absolute; TOP: 168px" width="336px">Label</asp:label></font>
18</form>
19</body>
20</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
{
///
1<summary>
2/// BookView 的摘要说明。
3/// </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);
}
///
1<summary>
2/// 设计器支持所需的方法 - 不要使用代码编辑器修改
3/// 此方法的内容。
4/// </summary>
private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
}
}
//购物车页面。实现此功能主要使用DataGrid来显示总计功能。
1@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="CartTest.WebForm1"
1<html>
2<head>
3<title>WebForm1</title>
4<meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR"/>
5<meta content="C#" name="CODE_LANGUAGE"/>
6<meta content="JavaScript" name="vs_defaultClientScript"/>
7<meta content=" http://schemas.microsoft.com/intellisense/ie5 " name="vs_targetSchema"/>
8<script>
9//此JS主要是防止用户输入非数字
10function checkNum()
11{
12var chr=String.fromCharCode(event.keyCode);
13
14if(isNaN(chr))
15{
16event.keyCode=0;
17}
18}
19
20</script>
21</head>
22<body ms_positioning="GridLayout">
23<form id="Form1" method="post" runat="server">
24<asp:datagrid autogeneratecolumns="False" bordercolor="SkyBlue" borderstyle="Solid" borderwidth="1px" cellpadding="4" datakeyfield="BookID" font-size="XX-Small" id="DataGrid1" pagesize="15" runat="server" showfooter="True" width="680px">
25<itemstyle backcolor="#EEEEEE"></itemstyle>
26<headerstyle backcolor="SkyBlue" font-bold="True" font-size="9pt"></headerstyle>
27<columns>
28<asp:templatecolumn headertext="书名">
29<itemtemplate>
30<asp:label id="Label2" runat="server" text='```
31# DataBinder.Eval(Container, "DataItem.Title")
32```'>
33</asp:label>
34</itemtemplate>
35</asp:templatecolumn>
36<asp:templatecolumn headertext="单价">
37<itemtemplate>
38<asp:textbox id="txtPrice" readonly="True" runat="server" text='```
39# DataBinder.Eval(Container, "DataItem.Price")
40```'>
41</asp:textbox>
42</itemtemplate>
43</asp:templatecolumn>
44<asp:templatecolumn headertext="数量">
45<itemtemplate>
46<asp:textbox id="txtNum" onkeypress="checkNum()" runat="server" text='```
47# DataBinder.Eval(Container, "DataItem.Num")
48```'>
49</asp:textbox>
50</itemtemplate>
51</asp:templatecolumn>
52<asp:templatecolumn headertext="总金额">
53<itemtemplate>
54<asp:textbox id="txtSum" readonly="True" runat="server" text='```
55# DataBinder.Eval(Container, "DataItem.Sum")
56```'>
57</asp:textbox>
58</itemtemplate>
59<footertemplate>
60<asp:textbox id="txtSumPrice" readonly="True" runat="server"></asp:textbox>
61</footertemplate>
62</asp:templatecolumn>
63<asp:templatecolumn headertext="操作">
64<itemtemplate>
65<asp:linkbutton commandname="editBook" id="LinkButton1" runat="server">修改</asp:linkbutton><font face="宋体"> </font>
66<asp:linkbutton commandname="delBook" id="LinkButton2" runat="server">删除</asp:linkbutton>
67</itemtemplate>
68</asp:templatecolumn>
69</columns>
70<pagerstyle backcolor="SkyBlue" font-names="webdings" font-size="10pt" nextpagetext="4" prevpagetext="3"></pagerstyle>
71</asp:datagrid>
72</form>
73</body>
74</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
{
///
1<summary>
2/// WebForm1 的摘要说明。
3/// </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);
}
///
1<summary>
2/// 设计器支持所需的方法 - 不要使用代码编辑器修改
3/// 此方法的内容。
4/// </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集合).当每个用户进入到网站时,首先给其分配一个空的购物车。当用户在购物页面选取一个货物时,取得该货物,同时获得自己的购物车,将货物保存到购物车中,最后再保存购物车。如果用户要对购物车中的内容进行修改也是一样的原理。而且在购物车察看页。我们则将自己生成的集合类对象绑定到我们的页面中。利用网格窗控年的一此事件来处理货物统计的问题。
希望这样一个思路能对您有所帮助。