.NEt专家博客!

asp.net 实现购物车详细代码

上一篇 / 下一篇  2008-07-03 14:42:29 / 个人分类:.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> 
Sl VgC5z0<title>shoppingcartITPUB个人空间lp1L6Kt^4h
</title> ITPUB个人空间I4NcF+`h#@\.En
<meta. http-equiv="Content-Type" content="text/html;
U tdl"c)i-@ q0charset=gb2312">  <LINK href="mycss.css" type="text/css" rel="stylesheet"> ITPUB个人空间R1kB'FJ
<meta. name="vs_defaultClientScript" content="JavaScript"> ITPUB个人空间4e*G2b9H R
<meta. name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">  </HEAD>ITPUB个人空间Z)u E!{Z~w
<body>  <center>  ITPUB个人空间[c)g&p`7P
<form. id="Form1" runat="server">    <table width="500" border="0" cellspacing="0" cellpadding="0">     <tr>      <td>      
U6p9pv p|5k}3]0<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>        
&u.OY%`B%N0<asp:TemplateColumn HeaderText="删除">         ITPUB个人空间w-R0T]&s#w
<ItemTemplate>           <center>           
*V%UA }of _Wn0<asp:CheckBox id="chkProductID" runat="server" />           </center>         
7Y2ov5d,~JG0</ItemTemplate>         </asp:TemplateColumn>        ITPUB个人空间L6NF$g~%W
<asp:BoundColumn DataField="ProdID" HeaderText="ID" />        
-]8U.P8K$L1DL1a:R/C0<asp:BoundColumn DataField="ProName" HeaderText="商品名称" />        ITPUB个人空间R3HP)?(O+v@ }
<asp:BoundColumn DataField="UnitPrice" HeaderText="单价" />        ITPUB个人空间0F1v[6U1p%c
<asp:TemplateColumn HeaderText="数量">         
j#n&MN1f2k4G0<ItemTemplate>          
N ~\9K'Yg J_0<asp:TextBox id="CountTb" runat="server" Text='<%#DataBinder.Eval( Container.DataItem,"ProdCount" )%>'>           </asp:TextBox>         ITPUB个人空间!o5A U0`)K4^Fr
</ItemTemplate>         </asp:TemplateColumn>        ITPUB个人空间g_*}Cb]Ch&[J
<asp:BoundColumn DataField="TotalPrice" HeaderText="小计( 元 )" />        </Columns>       </asp:DataGrid></td>     </tr>    </table>    <br>    <table width="500" border="0" cellspacing="0" cellpadding="0">     <tr>      <td>ITPUB个人空间6Yuse_7AkC|
<asp:Button id="update" runat="server" Text="更新我的购物车"  CssClass="button2" /></td>      <td>
v*MM_cs9Z-`K:d0<asp:Button id="CheckOut" runat="server" Text="结算"  CssClass="button5" />

<input type="button" name="close2" value="继续购物" nClick="window.close( );ITPUB个人空间 hr0S"e9W*S P;i~
return false;
)[Q2j#pyzQ C0"        class="button2"></td>      <td align="right"><br>      ITPUB个人空间!]R4r-q%N2R5|
<asp:Label id="label" runat="server" Width="100px" Visible="True" ForeColor="#FF8080" Height="18px"></asp:Label></td>     </tr>    </table>  
0}e/c[0@ojFj0</form>  </center>ITPUB个人空间NJMTDZ\
</body></HTML>=======================================================================================以上为HTML页面部分==========================================================================================ITPUB个人空间)U%|&V(B&w1qc7M
using System;
C[7G1~4A.q F(k+sz0using System.Collections;
E S4N ~X#{E4g^@YTL0using System.ComponentModel;ITPUB个人空间s;tF6O+r%e Y1z
using System.Web.SessionState;ITPUB个人空间o|*nko,C.tK
using System.Web;
!v+r7[q@0using System.Web.UI;
Y]E1sI*D(Kh(@ @ B`0using System.Web.UI.HtmlControls;ITPUB个人空间0I|8HOW2t2c*s t
using System.Web.UI.WebControls;
y.cZ!le#? e BwP0using System.Data;
FZ/kb#p$_.y0using System.Data.OleDb;ITPUB个人空间S1gUe!J ob
using System.Configuration;
@#W(?&sBU*T%v0namespace myshopITPUB个人空间'w8Y4K(xgfQ
{
3Ghq#I9Y0    /// <summary> /// shoppingcart 的摘要说明. /// </summary> public class shoppingcart : System.Web.UI.Page
H0EMJ:GY0    {ITPUB个人空间o3Qd(OvT
        protected System.Web.UI.WebControls.DataGrid ShoppingCartDlt;
2V^W9P0_0        protected System.Web.UI.WebControls.Button update;
[kj5X#OGq+R C|0        protected System.Web.UI.WebControls.Button CheckOut;ITPUB个人空间j\T'|9D*r;n
        protected System.Web.UI.HtmlControls.HtmlForm. Form1;
/Q5CE!`8ui)?n0        protected System.Web.UI.WebControls.Label label;ITPUB个人空间Zu&H0We
        protected System.Web.UI.WebControls.CheckBox     chkProductID;
-C-J`uH+P(W#ZE0        protected System.Web.UI.WebControls.TextBox      txtCount;ITPUB个人空间/JMYKHYh L
        protected System.Web.UI.WebControls.TextBox      CountTb;ITPUB个人空间,@]5J.Y&B aZt(y
        string AddProID;ITPUB个人空间H.?rRA*Om
        private void Page_Load( object sender, System.EventArgs e ) 
K;S~0]+@f2O V` Fg*Y0Q0        {
!g G~`e4^0            try  ITPUB个人空间3SnB&j.qs
            {ITPUB个人空间n5_ Az&\FE
                if ( Session["logon"]!="yes"||Session["username"]==null )   ITPUB个人空间$O^gri+\sgTe)?
                {ITPUB个人空间P6P;w!T-\ ^!K+]
                    Response.Redirect( "error.htm" ) ;ITPUB个人空间.T'N$L0rDX4N
                }ITPUB个人空间7`!m:y5y1@7AmS:Ui
            }ITPUB个人空间]D KLm1j+s(F;f
            catch  
J D4GY-y:W!B"M$j0            {
q \Ny(t(N0                Response.Redirect( "error.htm" ) ;ITPUB个人空间$l(SD4x.W+Q| [ [+W
            }ITPUB个人空间Kn0kLX-De
            /////////////查看用户是否已经登陆.
@B\| \ q\2v0            if( !IsPostBack )  
+u+p;ncz0            {
9E Jq+Z+u Z#n nn-H0                if( Request.Params["mode"]=="view" )         //检测是否为直接查看购物车.   ITPUB个人空间7b E#]J{u)g ] u9nM
                {ITPUB个人空间7l@Y"KY+?
                    ViewShoppingCart( );ITPUB个人空间3zzY6IWz?W
                    Caculator( );ITPUB个人空间K5TJT"[ r5O!vo'y4q
                }
` W]b!j,p3~q^0                if( Request.Params["productID"]!=null||Request.Params["productID"]!="" )   
*K D0X0hs#gnu!k:W0                {
4n.U)L!ql6L[H+i0                    AddProID=Request["productID"];ITPUB个人空间cuV ^4?&}}
                    UpdateShoppingCart( );
ECd U#i.p"{ \Df0                    Caculator( );ITPUB个人空间 JKT:t7hv&g-w
                }ITPUB个人空间z)~|mgB
            }
HM'hV `4@ Gw[qBf0            // 在此处放置用户代码以初始化页面 
W:wg3s`0nAV8G^$C0        }
gY^)p s0        public void CreateCartTable( )   //创建购物车 ITPUB个人空间:C x-l?FiW
        {
!_2V3k}/i ju0            DataSet ds = new DataSet( );ITPUB个人空间'bX{n!U,A*t/Q
            DataTable newDT=new DataTable( "CartTable" );
8~-?JD9D Hw3`0            ds.Tables.Add( newDT );ITPUB个人空间L(^7e0|o y2p'U\ P*p
            DataColumn newDC;
-RAb[I Z7k0            newDC=new DataColumn( "ProdID",System.Type.GetType( "System.Int32" ) );ITPUB个人空间yvU,BZ
            ds.Tables["CartTable"].Columns.Add( newDC );
^r"C f `P0            newDC=new DataColumn( "ProdCount",System.Type.GetType( "System.Int32" ) );
miB u8IV$K0            newDC.DefaultValue=1;
0Jx&? O5F z"c0            ds.Tables["CartTable"].Columns.Add( newDC );ITPUB个人空间IP5wPo
            newDC=new DataColumn( "ProName",System.Type.GetType( "System.String" ) );
,x H]V;H#b*pD~*p'Z0            ds.Tables["CartTable"].Columns.Add( newDC );
5? L N3g5O0            newDC=new DataColumn( "UnitPrice",System.Type.GetType( "System.Double" ) );ITPUB个人空间FAh?B~.d!X+M
            ds.Tables["CartTable"].Columns.Add( newDC );ITPUB个人空间vE:Z+lW.l
            newDC=new DataColumn( "TotalPrice",System.Type.GetType( "System.Double" ) );
/`pK*K:e3w0c0            ds.Tables["CartTable"].Columns.Add( newDC );
;a^-v}dOk$a!k0            newDC=new DataColumn( "IsDeleted",System.Type.GetType( "System.Int32" ) );ITPUB个人空间j_0d,W3MG'V
            newDC.DefaultValue=0;
e4O-q8uR1P0            //  public void WriteShoppingCart( ) 中 newDR[5]="0";
.t N6\~|r+rh3?0            行,已被注销,   ds.Tables["CartTable"].Columns.Add( newDC );ITPUB个人空间7eS7jK$xrx@
            Session["myCartTable"]=newDT;ITPUB个人空间NB_^Iy$W
            ShoppingCartDlt.DataSource=ds.Tables["CartTable"].DefaultView;
6Y4c K&n/E"B)Q*k0            ShoppingCartDlt.DataBind( );ITPUB个人空间#K@3x(?/b _#t"az@
        }
w*AMG,Y-m#h0        public void UpdateShoppingCart( ) 
k-_"U#zLSQ0        {
V;\ Kkb0            if( Session["myCartTable"]==null )//Session["myCartTable"]==null  
U(N3R0c X]9V0            {
p7Qg6PxX0                CreateCartTable( );ITPUB个人空间 ]EWW%MH7q%W1w
                //调用函数CreateCartTable( )新建一个DataTable    WriteShoppingCart( );ITPUB个人空间 ]0jIwQ0B
            }
C1Q@ }6o7A w0            else  ITPUB个人空间8B-c:Sq%^5ud
            {
O?2h$f!c0                //如果购物蓝中已有商品,则需要对购物信息表DataTable进行更新,并将其棒定到ShoppingCartDlt                      WriteShoppingCart( );
:Q'~p/Kw0            }
;K7g{az Sx0        }
8jh5D&{VA5S0        public void ViewShoppingCart( )                               //查看购物车 
b:Vcm@1z4S6~G T0        {
pj}f U'n9G0            if( Session["myCartTable"]!=null )  
UC1[F#_I:d"K0            {
6Rc0hEa;rj0                DataTable viewTable=new DataTable( "nowCartTable" );ITPUB个人空间/~o\%_(ON1S(~&I2y
                viewTable=( DataTable )Session["myCartTable"];
[z]"Lw:ZR-qo0                ShoppingCartDlt.DataSource = viewTable.DefaultView;
U#r]7n P BK!p;D0                //购物车棒定到ShoppingCartDlt    ShoppingCartDlt.DataBind( );ITPUB个人空间^7]+H @5W gD+e#p2c{
            }ITPUB个人空间FPC Zu f!q
        }ITPUB个人空间+L d%kSL8a(w]
        public void WriteShoppingCart( ) ITPUB个人空间x3f8iG2C
        {
%R_%q.OdJ2`K0B e0            if( Request.Params["mode"]!="view" )                             //检查是否是直接查看购物车,如果直接查看,就不再写MYCARTTABLE  ITPUB个人空间$nO'p;F$_t
            {
mPjY0K9[0                DataTable nowTable=new DataTable( "nowCartTable" );
!v q yv"I.gl H`e0                nowTable=( DataTable )Session["myCartTable"];
x zSr$q0                int pn=nowTable.Rows.Count;
;f1F3G7_)um9]*O&D0                int i=0;ITPUB个人空间_vF_*ub
                bool hasone=false;
%c4`?2~Y0                int nowProdID;ITPUB个人空间G%q,gZKr${.@7o
                while( i<pn && !hasone )   
SYa J9~pv ^r0                {ITPUB个人空间7^n`L+A:o*N
                    nowProdID=Int32.Parse( nowTable.Rows[i][0].ToString( ) );
]/pR'M7o.exA*k0                    if( nowProdID==Int32.Parse( AddProID ) )                                   //判断购物信息表中,是否存有当前放入商品. if( nowProdID==Int32.Parse( AddProID ) )    ITPUB个人空间Pl#B jl+bx
                    {ITPUB个人空间M-@J6ii t
                        hasone=true;ITPUB个人空间!v8r@zzb
                    }
oT*}vr~)R-W!|P0                    else    
H-|Z)j$W o!k0                    {
8C0Np%zh1yUb0                        i++;ITPUB个人空间0H KPLm`-g6q*}YB
                    }
~#~h#tY$MeoW9\0                }
6s)b1H/v| n5^0                if( hasone )                              
?Xm'l ZV0                {ITPUB个人空间W*~9Q$Fe7[L"b M5L*u
                    //如果已有该商品,则 hasone=true,更改该数据行     DataRow oldDR;
q/xN2o6T#a0                    ldDR=nowTable.Rows[i];ITPUB个人空间 ?-w|r}"h
                    oldDR["ProdCount"]=Int32.Parse( oldDR["ProdCount"].ToString( ) )+1;
o Wu_8K0                    oldDR["TotalPrice"]=Int32.Parse( oldDR["ProdCount"].ToString( ) )*Double.Parse( oldDR["UnitPrice"].ToString( ) );
X5B!R n~iCyQ0                }
t @7QWf!RB0                else   ITPUB个人空间(L1I,`K O q p!`aX
                {ITPUB个人空间 e I/?:iJ2Dt
                    //如果没有该商品,在表中新加如一行.     DataRow newDR;ITPUB个人空间 [ d Oe1lv
                    double unitp;ITPUB个人空间,B Z"G6^/a6j'ZW }
                    String strcon="provider=Microsoft.jet.OLEDB.4.0;
nqv.[3t;_!{!o!gx[0                    data Source="+Server.MapPath( ConfigurationSettings.AppSettings["MDBpath2"] )+";ITPUB个人空间t1@'f }A:tG
                    ";ITPUB个人空间.Dc0k's/js!l,LF
                    OleDbConnection myConnection = new OleDbConnection( strcon );ITPUB个人空间._S[RD
                    string strSQL= "select *  from pro where product_id="+AddProID+"";ITPUB个人空间b~ WzJ$f~
                    OleDbDataAdapter myCommand = new  OleDbDataAdapter( strSQL, myConnection );
S-??5whP$fL0                    DataSet ds = new DataSet( );ITPUB个人空间p~9e&e0m0Ip
                    myCommand.Fill( ds, "AddP" );ITPUB个人空间.Qg~bs-K*gW
                    newDR=nowTable.NewRow( );ITPUB个人空间j'SgmY? L3}
                    newDR[0]=AddProID;ITPUB个人空间$v,ro G5Jx\
                    newDR[2]=ds.Tables["Addp"].Rows[0]["product_name"].ToString( );
:ywG6?8n'c$a0                    unitp=Double.Parse( ds.Tables["AddP"].Rows[0]["product_memprice"].ToString( ) );
X+c)wFV3\4E0                    //会员价                            newDR[3]=unitp;
)fl;AFr3l*Wz0                    newDR[4]=unitp;
/] l5il;_bZ0                    //第一次读库,所以总价格和单价是一样的.     //newDR[5]="0";
'tYC fa$FB'[ ?Q0                    nowTable.Rows.Add( newDR );
7}#c(Q8FSfX0                    myConnection.Close( );ITPUB个人空间&UG N,_3m+\6rxty
                }
&L.Q6L Y_/v0                ShoppingCartDlt.DataSource = nowTable.DefaultView;ITPUB个人空间;B3H9S'G;w@4xj
                //将更新后的 DataTable棒定到ShoppingCartDlt    ShoppingCartDlt.DataBind( );
hI3{Nl5A6V0                Session["myCartTable"] = nowTable;
tz+v^-E^9W$I0                //重新保存更新过的DataTable  
I$R0qU)}*L9l9Pj d0            }ITPUB个人空间7[lM4d:up
        }ITPUB个人空间!c.Zj)w)Ll*r?
        public void Caculator( ) ITPUB个人空间d(M2?7m ht
        {ITPUB个人空间;DP:bq3])v(YB
            if( Session["myCartTable"]!=null )                         //购物车是否为空  
1~`(W1{Mam-G4S0            {ITPUB个人空间T"f.gmu
                int h;ITPUB个人空间#VYb5`xe/Y
                Double TotalPri;ITPUB个人空间[l7u&khLh8n3j!_
                TotalPri=0;ITPUB个人空间{m*m2xBWdND
                DataTable nowTable3=new DataTable( "nowCartTable3" );
N%a8@}#a@zT0g,U|0                nowTable3=( DataTable )Session["myCartTable"];ITPUB个人空间 O2SiX*N.m
                if( nowTable3.Rows.Count>0 )                               //返回购物车中是否有货物   ITPUB个人空间7UL4~|5L:Y"i
                {ITPUB个人空间)wiOe|%e
                    for( h=0;ITPUB个人空间+b3` z)qC \.it%^#K
                    h<=nowTable3.Rows.Count-1;
,m,b!e`Ap0                    h++ )    ITPUB个人空间0b7@Uc\X,w
                    {
,`;O y u^!A6^0                        TotalPri=TotalPri+Int32.Parse( nowTable3.Rows[h][4].ToString( ) );
I7NVL7ow2N0                        //Double.Parse( ( string )TotalText.Text );
z2i!jc@0                    }
9Lja+b p0                    label.Text="总计: "+TotalPri.ToString( )+" 元" ;
&TU'hn#t;|g0                }ITPUB个人空间LP tNFaw
            }
i_C:u'Xdk0T9R0        }ITPUB个人空间2x iG1mxL^x(r m
        public void Update( ) 
+F3ruR,{ Qk h8}0        {
3z4gTCfe[w0            int i;ITPUB个人空间ip]Uvyi"G W
            int j;
aH peHyv0            int k;ITPUB个人空间u#zdT-O w3J*o
            ArrayList deleteItem = new ArrayList( 10 );
AF)i^,`e0            DataGridItem _item ;ITPUB个人空间]\SA A/h
            j=0;ITPUB个人空间 { o|$s(X
            int deleteid;
/i~,Y cxk0            k=0;ITPUB个人空间T/Bw7z Yu"g
            DataTable nowTable2=new DataTable( "nowCartTable2" );ITPUB个人空间 u&D YB$@
            nowTable2=( DataTable )Session["myCartTable"];
Z,D$C@K0VM']0            for( i=0;
\*}RYe Bb3@*Ml0            i<=this.ShoppingCartDlt.Items.Count-1;
2ByP3~b$Y!I0            i++ )  
!M9X9ypR*m+e y0            {
&n3Ai N5`0                _item = this.ShoppingCartDlt.Items[i];ITPUB个人空间9~$[ LRU
                TextBox CountText=( TextBox )this.ShoppingCartDlt.Items[i].Cells[4].FindControl( "CountTb" );ITPUB个人空间me o&^h+{9i]tX
                //Controls[1];ITPUB个人空间o tJ|.H3ig
                //_item.FindControl( "CountTb" );ITPUB个人空间 [(h+g%CT
                CheckBox ProductIDCheck =( CheckBox ) _item.FindControl( "chkProductID" );
1e2vP,]Hxw0                nowTable2.Rows[i][1] = Int32.Parse( CountText.Text.ToString( ) );ITPUB个人空间;m8@F4pP,^7m/LW
                nowTable2.Rows[i][4] = Int32.Parse( nowTable2.Rows[i][1].ToString( ) ) * Double.Parse( nowTable2.Rows[i][3].ToString( ) );
&c$|.E^yM5b\&_0                if( ProductIDCheck.Checked )   
qJ|"S4m w-W1\j0                {ITPUB个人空间!~.j]o P k{T
                    nowTable2.Rows[i][5] = 1;ITPUB个人空间R!] Z'eqSL-Q
                    //添加删除标记1     j=j+1;ITPUB个人空间 } \di/NW
                }
\6rb"Z,e"qyrM7x0            }ITPUB个人空间6^C.W'wN qSbK
            string strExpr="IsDeleted>0";
q2Sj1?+SEK2xt0            //http://msdn.microsoft.com/library/chs/default.asp?url=/library/CHS/cpref/html/frlrfSystemDataDataTableClassSelectTopic.asp   DataRow[] foundRows = nowTable2.Select( strExpr );ITPUB个人空间sI%u Rn/l8d\
            for( int m = 0;ITPUB个人空间9` M"u+^1YN;^ydL
            m < foundRows.Length;ITPUB个人空间:i5A.Z C)b$kt}
            m ++ )  ITPUB个人空间Z-^!M6@3F
            {
|iU2S6S,K0                //Console.WriteLine( foundRows[i][0] );ITPUB个人空间;W"n9G8~y rb8u
                foundRows[m].Delete( );ITPUB个人空间n6dg ?th
            }ITPUB个人空间'\-X%O(M`K
            ShoppingCartDlt.DataSource = nowTable2.DefaultView;ITPUB个人空间3^.k)YJ J MK[cX
            ShoppingCartDlt.DataBind( );
:|;d_bxM S9V xyC0            Session["myCartTable"] = nowTable2;ITPUB个人空间*ynLmu
            Caculator( );
F3RL^%@ T/uP0        }
vkSd3G9z0        #region Web 窗体设计器生成的代码  override protected void OnInit( EventArgs e ) ITPUB个人空间LZIK^ G{k;VVE
        {ITPUB个人空间kX0j#y[-M
            //   // CODEGEN: 该调用是 asp.NET Web 窗体设计器所必需的.   //   InitializeComponent( );
"O.eM/@S0            base.OnInit( e );ITPUB个人空间4Jy q,uq9Z J
        }ITPUB个人空间Y z!_o_E
        /// <summary>  /// 设计器支持所需的方法 - 不要使用代码编辑器修改  /// 此方法的内容.  /// </summary>  private void InitializeComponent( ) 
1DCKk F+d4{)T0        {ITPUB个人空间B].d `)zFH,A8z9j/Q4q(z
            this.update.Click += new System.EventHandler( this.update_Click );
ice o u i\0            this.CheckOut.Click += new System.EventHandler( this.CheckOut_Click );ITPUB个人空间*B,?!i9q@,a&t
            this.Load += new System.EventHandler( this.Page_Load );ITPUB个人空间Z)z;o7?6bR(z
        }ITPUB个人空间7w%ztie,a
        #endregionITPUB个人空间-`S}1T;iyQ)y o
        private void update_Click( object sender, System.EventArgs e ) 
L qXK b0        {
%Nf]5E)dh'h0h0            Update( );
qti-s6lyU'sj0        }
C6g;@/s c*qf8e0        private void CheckOut_Click( object sender, System.EventArgs e ) 
E*zz!b@`U0        {
fRfFn4V0            Update( );
0U0@e8l iL8y2]_[%`0            Response.Redirect( "checkout.aspx" );
j"Ty!f\8a1L0        }
Q+?d%` w-wfN&|0    }ITPUB个人空间 Rk!?8B;\
}
IT SP6wK NW p0


TAG:

 

评分:0

我来说两句

显示全部

:loveliness: :handshake :victory: :funk: :time: :kiss: :call: :hug: :lol :'( :Q :L ;P :$ :P :o :@ :D :( :)

Open Toolbar