求asp.net2.0 一个完整的hashtable的购物车例子
求asp.net2.0 一个完整的hashtable的购物车例子不要太复杂的简单点就好了!
谢谢各位大虾了 --------------------编程问答-------------------- 不要掉队啊顶上去 --------------------编程问答-------------------- 文章来自的我的Blog
http://blog.csdn.net/octverve/archive/2007/09/04/1771087.aspx
=============================
asp.net 实现购物车详细代码
下次再有人问,就指给他、她看,省口水啊
<%@ Page language="c#" Codebehind="shoppingcart.aspx.cs" AutoEventWireup="false" Inherits="myshop.shoppingcart" %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" ><HTML> <HEAD>
<title>shoppingcart
</title>
<meta http-equiv="Content-Type" content="text/html;
charset=gb2312"> <LINK href="mycss.css" type="text/css" rel="stylesheet">
<meta name="vs_defaultClientScript" content="JavaScript">
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5"> </HEAD>
<body> <center>
<form id="Form1" runat="server"> <table width="500" border="0" cellspacing="0" cellpadding="0"> <tr> <td>
<asp:DataGrid id="ShoppingCartDlt" runat="server" Width="500" BackColor="white" BorderColor="black" ShowFooter="false" CellPadding="3" CellSpacing="0" Font-Name="Verdana" Font-Size="8pt" HeaderStyle-BackColor="#cecfd6" AutoGenerateColumns="false" MaintainState="true"> <Columns>
<asp:TemplateColumn HeaderText="删除">
<ItemTemplate> <center>
<asp:CheckBox id="chkProductID" runat="server" /> </center>
</ItemTemplate> </asp:TemplateColumn>
<asp:BoundColumn DataField="ProdID" HeaderText="ID" />
<asp:BoundColumn DataField="ProName" HeaderText="商品名称" />
<asp:BoundColumn DataField="UnitPrice" HeaderText="单价" />
<asp:TemplateColumn HeaderText="数量">
<ItemTemplate>
<asp:TextBox id="CountTb" runat="server" Text='<%#DataBinder.Eval( Container.DataItem,"ProdCount" )%>'> </asp:TextBox>
</ItemTemplate> </asp:TemplateColumn>
<asp:BoundColumn DataField="TotalPrice" HeaderText="小计( 元 )" /> </Columns> </asp:DataGrid></td> </tr> </table> <br> <table width="500" border="0" cellspacing="0" cellpadding="0"> <tr> <td>
<asp:Button id="update" runat="server" Text="更新我的购物车" CssClass="button2" /></td> <td>
<asp:Button id="CheckOut" runat="server" Text="结算" CssClass="button5" />
<input type="button" name="close2" value="继续购物" onClick="window.close( );
return false;
" class="button2"></td> <td align="right"><br>
<asp:Label id="label" runat="server" Width="100px" Visible="True" ForeColor="#FF8080" Height="18px"></asp:Label></td> </tr> </table>
</form> </center>
</body></HTML>=======================================================================================以上为HTML页面部分
==========================================================================================
using System;
using System.Collections;
using System.ComponentModel;
using System.Web.SessionState;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.OleDb;
using System.Configuration;
namespace myshop
{
/// <summary> /// shoppingcart 的摘要说明. /// </summary> public class shoppingcart : System.Web.UI.Page
{
protected System.Web.UI.WebControls.DataGrid ShoppingCartDlt;
protected System.Web.UI.WebControls.Button update;
protected System.Web.UI.WebControls.Button CheckOut;
protected System.Web.UI.HtmlControls.HtmlForm Form1;
protected System.Web.UI.WebControls.Label label;
protected System.Web.UI.WebControls.CheckBox chkProductID;
protected System.Web.UI.WebControls.TextBox txtCount;
protected System.Web.UI.WebControls.TextBox CountTb;
string AddProID;
private void Page_Load( object sender, System.EventArgs e )
{
try
{
if ( Session["logon"]!="yes" Session["username"]==null )
{
Response.Redirect( "error.htm" ) ;
}
}
catch
{
Response.Redirect( "error.htm" ) ;
}
/////////////查看用户是否已经登陆.
if( !IsPostBack )
{
if( Request.Params["mode"]=="view" ) //检测是否为直接查看购物车.
{
ViewShoppingCart( );
Caculator( );
}
if( Request.Params["productID"]!=null Request.Params["productID"]!="" )
{
AddProID=Request["productID"];
UpdateShoppingCart( );
Caculator( );
}
}
// 在此处放置用户代码以初始化页面
}
public void CreateCartTable( ) //创建购物车
{
DataSet ds = new DataSet( );
DataTable newDT=new DataTable( "CartTable" );
ds.Tables.Add( newDT );
DataColumn newDC;
newDC=new DataColumn( "ProdID",System.Type.GetType( "System.Int32" ) );
ds.Tables["CartTable"].Columns.Add( newDC );
newDC=new DataColumn( "ProdCount",System.Type.GetType( "System.Int32" ) );
newDC.DefaultValue=1;
ds.Tables["CartTable"].Columns.Add( newDC );
newDC=new DataColumn( "ProName",System.Type.GetType( "System.String" ) );
ds.Tables["CartTable"].Columns.Add( newDC );
newDC=new DataColumn( "UnitPrice",System.Type.GetType( "System.Double" ) );
ds.Tables["CartTable"].Columns.Add( newDC );
newDC=new DataColumn( "TotalPrice",System.Type.GetType( "System.Double" ) );
ds.Tables["CartTable"].Columns.Add( newDC );
newDC=new DataColumn( "IsDeleted",System.Type.GetType( "System.Int32" ) );
newDC.DefaultValue=0;
// public void WriteShoppingCart( ) 中 newDR[5]="0";
行,已被注销, ds.Tables["CartTable"].Columns.Add( newDC );
Session["myCartTable"]=newDT;
ShoppingCartDlt.DataSource=ds.Tables["CartTable"].DefaultView;
ShoppingCartDlt.DataBind( );
}
public void UpdateShoppingCart( )
{
if( Session["myCartTable"]==null )//Session["myCartTable"]==null
{
CreateCartTable( );
//调用函数CreateCartTable( )新建一个DataTable WriteShoppingCart( );
}
else
{
//如果购物蓝中已有商品,则需要对购物信息表DataTable进行更新,并将其棒定到ShoppingCartDlt WriteShoppingCart( );
}
}
public void ViewShoppingCart( ) //查看购物车
{
if( Session["myCartTable"]!=null )
{
DataTable viewTable=new DataTable( "nowCartTable" );
viewTable=( DataTable )Session["myCartTable"];
ShoppingCartDlt.DataSource = viewTable.DefaultView;
//购物车棒定到ShoppingCartDlt ShoppingCartDlt.DataBind( );
}
}
--------------------编程问答-------------------- 文章来自的我的Blog
http://blog.csdn.net/octverve/archive/2007/09/04/1771087.aspx
=============================
asp.net 实现购物车详细代码
下次再有人问,就指给他、她看,省口水啊
<%@ Page language="c#" Codebehind="shoppingcart.aspx.cs" AutoEventWireup="false" Inherits="myshop.shoppingcart" %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" ><HTML> <HEAD>
<title>shoppingcart
</title>
<meta http-equiv="Content-Type" content="text/html;
charset=gb2312"> <LINK href="mycss.css" type="text/css" rel="stylesheet">
<meta name="vs_defaultClientScript" content="JavaScript">
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5"> </HEAD>
<body> <center>
<form id="Form1" runat="server"> <table width="500" border="0" cellspacing="0" cellpadding="0"> <tr> <td>
<asp:DataGrid id="ShoppingCartDlt" runat="server" Width="500" BackColor="white" BorderColor="black" ShowFooter="false" CellPadding="3" CellSpacing="0" Font-Name="Verdana" Font-Size="8pt" HeaderStyle-BackColor="#cecfd6" AutoGenerateColumns="false" MaintainState="true"> <Columns>
<asp:TemplateColumn HeaderText="删除">
<ItemTemplate> <center>
<asp:CheckBox id="chkProductID" runat="server" /> </center>
</ItemTemplate> </asp:TemplateColumn>
<asp:BoundColumn DataField="ProdID" HeaderText="ID" />
<asp:BoundColumn DataField="ProName" HeaderText="商品名称" />
<asp:BoundColumn DataField="UnitPrice" HeaderText="单价" />
<asp:TemplateColumn HeaderText="数量">
<ItemTemplate>
<asp:TextBox id="CountTb" runat="server" Text='<%#DataBinder.Eval( Container.DataItem,"ProdCount" )%>'> </asp:TextBox>
</ItemTemplate> </asp:TemplateColumn>
<asp:BoundColumn DataField="TotalPrice" HeaderText="小计( 元 )" /> </Columns> </asp:DataGrid></td> </tr> </table> <br> <table width="500" border="0" cellspacing="0" cellpadding="0"> <tr> <td>
<asp:Button id="update" runat="server" Text="更新我的购物车" CssClass="button2" /></td> <td>
<asp:Button id="CheckOut" runat="server" Text="结算" CssClass="button5" />
<input type="button" name="close2" value="继续购物" onClick="window.close( );
return false;
" class="button2"></td> <td align="right"><br>
<asp:Label id="label" runat="server" Width="100px" Visible="True" ForeColor="#FF8080" Height="18px"></asp:Label></td> </tr> </table>
</form> </center>
</body></HTML>=======================================================================================以上为HTML页面部分
==========================================================================================
using System;
using System.Collections;
using System.ComponentModel;
using System.Web.SessionState;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.OleDb;
using System.Configuration;
namespace myshop
{
/// <summary> /// shoppingcart 的摘要说明. /// </summary> public class shoppingcart : System.Web.UI.Page
{
protected System.Web.UI.WebControls.DataGrid ShoppingCartDlt;
protected System.Web.UI.WebControls.Button update;
protected System.Web.UI.WebControls.Button CheckOut;
protected System.Web.UI.HtmlControls.HtmlForm Form1;
protected System.Web.UI.WebControls.Label label;
protected System.Web.UI.WebControls.CheckBox chkProductID;
protected System.Web.UI.WebControls.TextBox txtCount;
protected System.Web.UI.WebControls.TextBox CountTb;
string AddProID;
private void Page_Load( object sender, System.EventArgs e )
{
try
{
if ( Session["logon"]!="yes" Session["username"]==null )
{
Response.Redirect( "error.htm" ) ;
}
}
catch
{
Response.Redirect( "error.htm" ) ;
}
/////////////查看用户是否已经登陆.
if( !IsPostBack )
{
if( Request.Params["mode"]=="view" ) //检测是否为直接查看购物车.
{
ViewShoppingCart( );
Caculator( );
}
if( Request.Params["productID"]!=null Request.Params["productID"]!="" )
{
AddProID=Request["productID"];
UpdateShoppingCart( );
Caculator( );
}
}
// 在此处放置用户代码以初始化页面
}
public void CreateCartTable( ) //创建购物车
{
DataSet ds = new DataSet( );
DataTable newDT=new DataTable( "CartTable" );
ds.Tables.Add( newDT );
DataColumn newDC;
newDC=new DataColumn( "ProdID",System.Type.GetType( "System.Int32" ) );
ds.Tables["CartTable"].Columns.Add( newDC );
newDC=new DataColumn( "ProdCount",System.Type.GetType( "System.Int32" ) );
newDC.DefaultValue=1;
ds.Tables["CartTable"].Columns.Add( newDC );
newDC=new DataColumn( "ProName",System.Type.GetType( "System.String" ) );
ds.Tables["CartTable"].Columns.Add( newDC );
newDC=new DataColumn( "UnitPrice",System.Type.GetType( "System.Double" ) );
ds.Tables["CartTable"].Columns.Add( newDC );
newDC=new DataColumn( "TotalPrice",System.Type.GetType( "System.Double" ) );
ds.Tables["CartTable"].Columns.Add( newDC );
newDC=new DataColumn( "IsDeleted",System.Type.GetType( "System.Int32" ) );
newDC.DefaultValue=0;
// public void WriteShoppingCart( ) 中 newDR[5]="0";
行,已被注销, ds.Tables["CartTable"].Columns.Add( newDC );
Session["myCartTable"]=newDT;
ShoppingCartDlt.DataSource=ds.Tables["CartTable"].DefaultView;
ShoppingCartDlt.DataBind( );
}
public void UpdateShoppingCart( )
{
if( Session["myCartTable"]==null )//Session["myCartTable"]==null
{
CreateCartTable( );
//调用函数CreateCartTable( )新建一个DataTable WriteShoppingCart( );
}
else
{
//如果购物蓝中已有商品,则需要对购物信息表DataTable进行更新,并将其棒定到ShoppingCartDlt WriteShoppingCart( );
}
}
public void ViewShoppingCart( ) //查看购物车
{
if( Session["myCartTable"]!=null )
{
DataTable viewTable=new DataTable( "nowCartTable" );
viewTable=( DataTable )Session["myCartTable"];
ShoppingCartDlt.DataSource = viewTable.DefaultView;
//购物车棒定到ShoppingCartDlt ShoppingCartDlt.DataBind( );
}
}
--------------------编程问答-------------------- 帮顶 --------------------编程问答-------------------- 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 System.Data.SqlClient;
public partial class Controls_ProductList : System.Web.UI.UserControl
{
private DataTable tabProduct;
private DataTable tabCart;
protected int totalCount = 0;
protected int totalPrice = 0;
private DataTable ProductTable()
{
tabProduct = new DataTable();
string connStr = System.Configuration.ConfigurationSettings.AppSettings["DSN"];
SqlConnection cn = new SqlConnection(connStr);
SqlDataAdapter adp = new SqlDataAdapter("select ProductID,ProductName,ProductPrice from ParticularList", cn);
DataSet dst = new DataSet();
cn.Open();
adp.Fill(dst, "ProductTable");
cn.Close();
tabProduct = dst.Tables[0];
//使"ProductID"成为主键
DataColumn[] pkColumn = new DataColumn[1];
pkColumn[0] = tabProduct.Columns["ProductID"];
tabProduct.PrimaryKey = pkColumn;
return tabProduct;
}
private DataTable CartTable()
{
tabCart = new DataTable();
DataColumn cartColumn = new DataColumn();
cartColumn.DataType = System.Type.GetType("System.Int32");
cartColumn.ColumnName = "ProductID";
cartColumn.Unique = true;
tabCart.Columns.Add(cartColumn);
cartColumn = new DataColumn();
cartColumn.DataType = System.Type.GetType("System.String");
cartColumn.ColumnName = "ProductName";
tabCart.Columns.Add(cartColumn);
cartColumn = new DataColumn();
cartColumn.DataType = System.Type.GetType("System.String");
cartColumn.ColumnName = "ProductPrice";
tabCart.Columns.Add(cartColumn);
cartColumn = new DataColumn();
cartColumn.DataType = System.Type.GetType("System.Int32");
cartColumn.ColumnName = "ProductQuantity";
tabCart.Columns.Add(cartColumn);
//使"ProductID"成为主键
DataColumn[] pkColumns = new DataColumn[1];
pkColumns[0] = tabCart.Columns["ProductID"];
tabCart.PrimaryKey = pkColumns;
return tabCart;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["tabCart"] == null)
{
Session["tabProduct"] = ProductTable();
Session["tabCart"] = CartTable();
grvShoppingCart.DataSource = Session["tabCart"];
grvShoppingCart.DataBind();
}
else
{
grvShoppingCart.DataSource = Session["tabCart"];
grvShoppingCart.DataBind();
}
}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
int rowIndex = ((GridViewRow)(((LinkButton)e.CommandSource).NamingContainer)).RowIndex;
AddToCart(Convert.ToInt32(GridView1.DataKeys[rowIndex].Value));
}
protected void AddToCart(int ProductID)
{
DataTable tabCart = Session["tabCart"] as DataTable;
//循环遍历购物车并检查是否该项已经存在
bool found = false;
for (int i = 0; i < tabCart.Rows.Count; i++)
{
if (Convert.ToInt32(tabCart.Rows[i]["ProductID"]) == ProductID)
{
//增加数量并且标记为已发现
tabCart.Rows[i]["ProductQuantity"] = Convert.ToInt32(tabCart.Rows[i]["ProductQuantity"]) + 1;
found = true;
//当我们已经找到一项时跳出循环
break;
}
}
//如果该项没有找到,则把它添加为一个新行
if (!found)
{
DataTable tabProduct = Session["tabProduct"] as DataTable;
DataRow drProduct = tabProduct.Rows.Find(ProductID);
//从数据源中得到了需要的数据,把一个新行添加到购物车中
DataRow newRow = tabCart.NewRow();
newRow["ProductID"] = drProduct["ProductID"];
newRow["ProductName"] = drProduct["ProductName"];
newRow["ProductPrice"] = drProduct["ProductPrice"];
newRow["ProductQuantity"] = 1;
tabCart.Rows.Add(newRow);
}
//把新更新的购物篮存储回会话中
Session["tabCart"] = tabCart;
//更新购物篮,也即是"重新绑定它"
updateShopCart();
} --------------------编程问答-------------------- private void updateShopCart()
{
DataTable tabCart = Session["tabCart"] as DataTable;
grvShoppingCart.DataSource = tabCart;
grvShoppingCart.DataBind();
}
protected void grvShoppingCart_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
int count = Convert.ToInt32(((TextBox)((GridViewRow)e.Row).FindControl("txtCount")).Text);
int price = Convert.ToInt32(((Label)((GridViewRow)e.Row).FindControl("lblProPrice")).Text);
totalCount += count;
totalPrice += count * price;
}
}
protected void grvShoppingCart_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Empty")
{
DataTable tabCart = Session["tabCart"] as DataTable;
tabCart.Rows.Clear();
//把新更新的购物篮存储回会话中
Session["tabCart"] = tabCart;
//更新购物篮,也即是"重新绑定它"
updateShopCart();
}
else if (e.CommandName == "Updt")
{
UpdateGoodsCount();
}
else if (e.CommandName == "Buy")
{
Response.Redirect("CheckOutPage.aspx");
}
}
protected void grvShoppingCart_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
RemoveCart(Convert.ToInt32(grvShoppingCart.DataKeys[e.RowIndex].Value));
}
private void RemoveCart(int ProductID)
{
DataTable tabCart = Session["tabCart"] as DataTable;
DataRow drProduct = tabCart.Rows.Find(ProductID);
tabCart.Rows.Remove(drProduct);
//把新更新的购物篮存储回会话中
Session["tabCart"] = tabCart;
//更新购物篮,也即是"重新绑定它"
updateShopCart();
}
private void UpdateGoodsCount()
{
int rowIndex;
DataTable tabCart = Session["tabCart"] as DataTable;
for (int i = 0; i < grvShoppingCart.Rows.Count;i++ )
{
rowIndex = grvShoppingCart.Rows[i].RowIndex;
for (int j = 0; j < tabCart.Rows.Count; j++)
{
if (Convert.ToInt32(grvShoppingCart.DataKeys[rowIndex].Value) == Convert.ToInt32(tabCart.Rows[j]["ProductID"]))
{
if (((TextBox)grvShoppingCart.Rows[i].FindControl("txtCount")).Text != tabCart.Rows[j]["ProductQuantity"])
{
try
{
int quant = Convert.ToInt32(((TextBox)grvShoppingCart.Rows[i].FindControl("txtCount")).Text);
if (quant > 0)
{
tabCart.Rows[j]["ProductQuantity"] = ((TextBox)grvShoppingCart.Rows[i].FindControl("txtCount")).Text;
}
}
catch(Exception ex)
{
//Response.Write(ex.Message);
Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('输入数量有误,请输入数字!')</script>");
}
break;
}
}
}
}
//把新更新的购物篮存储回会话中
Session["tabCart"] = tabCart;
//更新购物篮,也即是"重新绑定它"
updateShopCart();
}
}
--------------------编程问答-------------------- 好复杂啊 --------------------编程问答-------------------- 不复杂那自己做一个去 --------------------编程问答-------------------- 用Response传值啊 --------------------编程问答-------------------- 在DataSet中创建一个DataTable,并把DataTable保存至Session中! --------------------编程问答-------------------- UP+mark,楼上的代码都不错
补充:.NET技术 , ASP.NET