vs2005+sql2005实现购物车功能

/***********************SQL 2005数据库设计如下:************************/

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Products]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Products](
 [ID] [int] IDENTITY(1,1) NOT NULL,
 [Quantity] [int] NOT NULL CONSTRAINT [DF_Products_Quantity]  DEFAULT ((0)),
 [Name] [varchar](50) NOT NULL,
 [UnitPrice] [money] NOT NULL,
 [TotalPrice]  AS ([Quantity]*[UnitPrice]),
 [IsDeleted] [int] NOT NULL CONSTRAINT [DF_Products_IsDeleted]  DEFAULT ((1)),
 CONSTRAINT [PK_Products] PRIMARY KEY CLUSTERED
(
 [ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END

/***********************VS2005 shoppingcart.aspx页面代码如下:*********************/

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="shoppingcart.aspx.cs" Inherits="shoppingcart" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>实现购物车</title>
</head>
<body>
    <center>
        <form id="Form1" runat="server">
            <table width="500" border="0" cellspacing="0" cellpadding="0" style="font-size:12px;">
                <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="ID" HeaderText="编号" />
                                <asp:BoundColumn DataField="Name" HeaderText="商品名称" />
                                <asp:BoundColumn DataField="UnitPrice" HeaderText="单价" DataFormatString="{0:C}" />
                                <asp:TemplateColumn HeaderText="数量">
                                    <ItemTemplate>
                                        <asp:TextBox ID="txtQuantity"  MaxLength="4" runat="server" Text='<%#DataBinder.Eval( Container.DataItem,"Quantity" )%>'></asp:TextBox>
                                    </ItemTemplate>
                                </asp:TemplateColumn>
                                <asp:BoundColumn DataField="TotalPrice" HeaderText="小计(元)" DataFormatString="{0:C}" />
                            </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="更新我的购物车" OnClick="update_Click" /></td>
                    <td>
                        <asp:Button ID="CheckOut" runat="server" Text="结算" CssClass="button5" />
                        <input type="button" name="close2" value="继续购物" οnclick="window.close();return false;" /></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>

 

/**************************VS2005 shoppingcart.aspx.cs代码如下**************************/

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 shoppingcart : System.Web.UI.Page
{
    string id = string.Empty;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Request.Params["mode"] == "view")         //检测是否为直接查看购物车.   
            {
                ViewShoppingCart();
                Caculator();
            }
            if (Request.QueryString["id"] != null)
            {
                id = Request["id"];
                UpdateShoppingCart();
                Caculator();
            }
            else
            {
                CreateCartTable();
            }
        }
    }
    public void Caculator()
    {
        //购物车是否为空
        if (Session["myCartTable"] != null)
        {
            int h;
            Double TotalPri;
            TotalPri = 0;
            DataTable nowTable3 = new DataTable("nowCartTable3");
            nowTable3 = (DataTable)Session["myCartTable"];
            if (nowTable3.Rows.Count > 0)                               //返回购物车中是否有货物   
            {
                for (h = 0;h <= nowTable3.Rows.Count - 1;h++)
                {
                    TotalPri = TotalPri + Int32.Parse(nowTable3.Rows[h][4].ToString());
                }
              
            }
            label.Text = "总计¥" + TotalPri.ToString() + ".00元";
        }
    }
    public void CreateCartTable()   //创建购物车 
    {
        DataSet ds = new DataSet();
        DataTable dt = new DataTable("CartTable");
        ds.Tables.Add(dt);
        DataColumn dc;
        dc=new DataColumn("ID",System.Type.GetType("System.Int32"));
        ds.Tables["CartTable"].Columns.Add(dc);

        dc = new DataColumn("Quantity", System.Type.GetType("System.Int32"));
        dc.DefaultValue=1;
        ds.Tables["CartTable"].Columns.Add(dc);

        dc=new DataColumn("Name",System.Type.GetType("System.String"));
        ds.Tables["CartTable"].Columns.Add(dc);

        dc=new DataColumn("UnitPrice",System.Type.GetType("System.Double") );
        ds.Tables["CartTable"].Columns.Add(dc);

        dc=new DataColumn("TotalPrice",System.Type.GetType("System.Double"));
        ds.Tables["CartTable"].Columns.Add(dc);

        dc=new DataColumn("IsDeleted",System.Type.GetType("System.Int32"));
        dc.DefaultValue=0; //0表示未删除 1表示己删除
        ds.Tables["CartTable"].Columns.Add(dc);

        Session["myCartTable"]=dt;
        ShoppingCartDlt.DataSource=ds.Tables["CartTable"].DefaultView;
        ShoppingCartDlt.DataBind();
    }
    public void UpdateShoppingCart()
    {
        if (Session["myCartTable"] == null) 
        {
            CreateCartTable();
            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.DataBind( );
        }
    }

    public void WriteShoppingCart( ) 
    {
        //检查是否是直接查看购物车,如果直接查看,就不再写myCartTable 
        if( Request.Params["mode"] != "view")
        {
            DataTable nowTable=new DataTable("nowCartTable");
            nowTable = Session["myCartTable"] as DataTable;
            int rowNumber = nowTable.Rows.Count;
            int i = 0;
            bool hasone = false;
            int nowProdID = 0;
            while (i < rowNumber && !hasone)   
            {
                nowProdID=Int32.Parse(nowTable.Rows[i][0].ToString());
                if(nowProdID==Int32.Parse(id))                                   //判断购物信息表中,是否存有当前放入商品. if( nowProdID==Int32.Parse( AddProID ) )    
                {
                    hasone = true;
                }
                else    
                {
                    i++;
                }
            }
            if(hasone)                              
            {
                //如果已有该商品,则hasone=true,更改该数据行
                DataRow oldDr;
                oldDr = nowTable.Rows[i];
                oldDr["Quantity"] = Int32.Parse(oldDr["Quantity"].ToString()) + 1;
                oldDr["TotalPrice"] = Int32.Parse(oldDr["Quantity"].ToString()) * Double.Parse(oldDr["UnitPrice"].ToString());
            }
            else   
            {
                //如果没有该商品,在表中新加入一行.    
                DataRow dr;
                double UnitPrice;
                string connString = "SERVER=.;DATABASE=Region;UID=sa;PWD=1;";
                SqlConnection conn = new SqlConnection(connString);
                string strSQL= "SELECT * FROM Products WHERE ID="+id+"";
                SqlDataAdapter sda = new SqlDataAdapter(strSQL, conn);
                DataSet ds = new DataSet();
                sda.Fill(ds, "Product");
                dr = nowTable.NewRow();
                dr[0]= id;
               
                dr[2] = ds.Tables["Product"].Rows[0]["Name"].ToString();
                UnitPrice = Double.Parse(ds.Tables["Product"].Rows[0]["UnitPrice"].ToString());
               
                dr[3] = UnitPrice;
                dr[4] = UnitPrice;
                dr[5]="0";
                nowTable.Rows.Add(dr);
                conn.Close();
                conn.Dispose();
            }
            ShoppingCartDlt.DataSource = nowTable.DefaultView; 
            ShoppingCartDlt.DataBind();
            Session["myCartTable"] = nowTable;
        }
    }

    public void Update()
    {
        int i;
        int j;
        ArrayList deleteItem = new ArrayList(10);
        DataGridItem _item;
        j = 0;
        DataTable nowTable2 = new DataTable("nowCartTable2");
        nowTable2 = (DataTable)Session["myCartTable"];
        for (i = 0;i <= this.ShoppingCartDlt.Items.Count - 1;i++)
        {
            _item = this.ShoppingCartDlt.Items[i];
            TextBox CountText = (TextBox)this.ShoppingCartDlt.Items[i].Cells[4].FindControl("txtQuantity");
            CheckBox ProductIDCheck = (CheckBox)_item.FindControl("chkProductID");
            nowTable2.Rows[i][1] = Int32.Parse(CountText.Text.ToString());
            nowTable2.Rows[i][4] = Int32.Parse(nowTable2.Rows[i][1].ToString()) * Double.Parse(nowTable2.Rows[i][3].ToString());
            if (ProductIDCheck.Checked)
            {
                nowTable2.Rows[i][5] = 1;//添加删除标记1
            }
        }
        string strExpr = "IsDeleted>0";
        DataRow[] foundRows = nowTable2.Select(strExpr);
        for (int m = 0;m < foundRows.Length;m++)
        {
            foundRows[m].Delete();
        }
        ShoppingCartDlt.DataSource = nowTable2.DefaultView;
        ShoppingCartDlt.DataBind();
        Session["myCartTable"] = nowTable2;
        Caculator();
    }
    protected void update_Click(object sender, EventArgs e)
    {
        Update();
    }
}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值