ASP.NET用GridView控件实现购物车功能

1、 将test数据库附加到数据库管理系统中;数据库中的book_info包含下列数据:

2、 新建一个网站,将images文件夹复制到网站中;
3、 在Default.aspx中,通过DataList控件展示数据库中的所有数据,以行为主序,每行3列,单击购买按钮时,将商品的ID和数量保存到HashTable中,并将HashTable放置到Session中。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
protected void DataList1_ItemCommand( object source, DataListCommandEventArgs e)
   {
     string id = e.CommandArgument.ToString();
     Hashtable ht;
     if (Session[ "shopcar" ] == null )
     {
       ht = new Hashtable();
       ht.Add(id, 1);
       Session[ "shopcar" ] = ht;
     }
     else
     {
       ht = (Hashtable)Session[ "shopcar" ];
       if (ht.Contains(id))
       {
         int count = int .Parse(ht[id].ToString());
         ht[id] = count + 1;
         Session[ "shopcar" ] = ht;
         Response.Write(count + 1);
       }
       else
       {
         ht.Add(id, 1);
         Session[ "shopcar" ] = ht;
       }
     }
   }

4、 在Default.aspx中添加一个超链接,链接到shopcart.aspx,在shopcart.aspx中显示用户购买的商品信息。
提示:

A、在shopcart中先定义下列变量:

?
1
2
3
4
5
6
Hashtable ht;
   DataTable dt;
   string connstring= @"DataSource=.\SQLEXPRESS;Initial Catalog=test;Integrated Security=True" ;
   SqlConnection conn;
   SqlCommand cmd;
  SqlDataReader sdr;

B、页面中添加一个GridView。
C、在page_load中,将dt实例化,建立各列。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
protected void Page_Load(object sender, EventArgs e)
   {
     dt = new DataTable();
     DataColumn col = new DataColumn();
     col.ColumnName= "id";
     col.DataType =System.Type.GetType("System.String");
     dt.Columns.Add(col);
     col = new DataColumn();
     col.ColumnName= "name";
     col.DataType =System.Type.GetType("System.String");
     dt.Columns.Add(col);
     col = new DataColumn();
     col.ColumnName= "Num";
     col.DataType =System.Type.GetType("System.Int32");
     dt.Columns.Add(col);
     col = new DataColumn();
     col.ColumnName= "price";
     col.DataType =System.Type.GetType("System.Single");
     dt.Columns.Add(col);
     col = new DataColumn();
     col.ColumnName= "Total";
     col.DataType =System.Type.GetType("System.Single");
     dt.Columns.Add(col);
     if (!IsPostBack)
     {
       Bind();
     }
   }
  
  
   public void Bind()
   {
     
  
     if (Session["shopcar"] == null)
     {
       Response.Write("< script >if(confirm('你没有登录')window.location='Default15.aspx';else window.close();</ script >");
     }
     else
     {
       ht = (Hashtable)Session["shopcar"];
       foreach (object item in ht.Keys)
       {
         string id = item.ToString();
         int num = int.Parse(ht[item].ToString());
         string sql = "selectbook_name,price from book_info where book_id='" + id + "'";
         conn = new SqlConnection(connstring);
         cmd = new SqlCommand(sql, conn);
         conn.Open();
         sdr =cmd.ExecuteReader();
         if (sdr.HasRows)
         {
           sdr.Read();
           DataRow row = dt.NewRow();
           row["id"] = id;
           row["Num"] = num;
           row["name"] = sdr.GetString(0);
           row["price"] =float.Parse(sdr[1].ToString());
           row["total"] =num*(float.Parse(sdr[1].ToString()));
           dt.Rows.Add(row);
         }
         sdr.Close();
         conn.Close();
                
       }
       GridView1.DataSource = dt.DefaultView;
       GridView1.DataBind();
     }
}

D、这时可以看到用户购买的商品,但不能修改数量,也不能删除。
E、添加修改数量,删除商品功能,在aspx页面中定义GridView中的各列:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<asp:GridView ID= "GridView1" runat= "server" AutoGenerateColumns= "False" >
     <Columns>
       <asp:BoundField DataField= "id" HeaderText= "ID" />
       <asp:BoundField DataField= "name" HeaderText= "名称" />
       <asp:BoundField DataField= "price" HeaderText= "价格" />
       <asp:TemplateField>     
        <ItemTemplate>
         <asp:TextBox runat= "server" ID= "textbox1" Text= '<%# Eval("Num") %>'
            ontextchanged= "textbox1_TextChanged" AutoPostBack= "True" ></asp:TextBox>
        </ItemTemplate>     
       </asp:TemplateField>
      <asp:BoundField DataField= "total" HeaderText= "总计" />
      <asp:TemplateField>
       <ItemTemplate>
        <asp:Button runat= "server" ID= "button1" CommandArgument= '<%# Eval("id") %>'
           Text= "删除" onclick= "button1_Click" />
       
       </ItemTemplate>
      
      </asp:TemplateField>
     </Columns>    
    </asp:GridView>

F、为GridView中的文本框添加TextChanged事件:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
protected void textbox1_TextChanged( object sender, EventArgs e)
   {
     
     Hashtable ht =(Hashtable)Session[ "shopcar" ];
     if (ht == null ) return ;
     for ( int i = 0; i < GridView1.Rows.Count;i++)
     {
       string id =GridView1.Rows[i].Cells[0].Text.ToString();
       Response.Write(id);
       string num = ((TextBox)GridView1.Rows[i].FindControl( "textbox1" )).Text;
       Response.Write( "  " +num+ "<br />" );
       ht[id] = num;
     }
     Session[ "shopcar" ] = ht;
     Bind();
    
   }

G、为按钮添加单击事件:

?
1
2
3
4
5
6
7
8
protected void button1_Click( object sender, EventArgs e)
   {
     string id = ((Button)sender).CommandArgument;
     Hashtable ht = (Hashtable)Session[ "shopcar" ];
     if (ht == null ) return ;
     ht.Remove(id);
     Bind();
}

购物车代码:showcart.aspx.cs

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.Data;
using System.Data.SqlClient;
  
public partial class shopcart : System.Web.UI.Page
{
   Hashtable ht;
   DataTable dt;
   string connstr = "Data Source=.\\SQLEXPRESS;AttachDbFilename=F:
 
\\test.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
   SqlConnection conn;
   SqlCommand cmd;
   SqlDataReader sdr;
   protected void Page_Load( object sender, EventArgs e)
   {
     dt = new DataTable();
     DataColumn col = new DataColumn();
     col.ColumnName = "id" ;
     col.DataType = System.Type.GetType( "System.String" );
     dt.Columns.Add(col);
     col = new DataColumn();
     col.ColumnName = "name" ;
     col.DataType = System.Type.GetType( "System.String" );
     dt.Columns.Add(col);
     col = new DataColumn();
     col.ColumnName = "Num" ;
     col.DataType = System.Type.GetType( "System.Int32" );
     dt.Columns.Add(col);
     col = new DataColumn();
     col.ColumnName = "price" ;
     col.DataType = System.Type.GetType( "System.Single" );
     dt.Columns.Add(col);
     col = new DataColumn();
     col.ColumnName = "Total" ;
     col.DataType = System.Type.GetType( "System.Single" );
     dt.Columns.Add(col);
  
     if (!IsPostBack)
     {
       Bind();
     }
  
   }
  
   public void Bind()
   {
     if (Session[ "shopcar" ] == null )
     {
       Response.Write( "<script>if(confirm('你没有登录')window.location='Default.aspx';else window.close();</script>" );
     }
     else
     {
       ht = (Hashtable)Session[ "shopcar" ];
       foreach ( object item in ht.Keys)
       {
         string id = item.ToString();
  
         int num = int .Parse((ht[item].ToString()));
         string sql = "select book_name,price from book_info where book_id='" + id + "'" ;
         conn = new SqlConnection(connstr);
  
         cmd = new SqlCommand(sql, conn);
         conn.Open();
  
         sdr = cmd.ExecuteReader();
         if (sdr.HasRows)
         {
           sdr.Read();
           DataRow row = dt.NewRow();
           row[ "id" ] = id;
           row[ "Num" ] = num;
           row[ "name" ] = sdr.GetString(0);
           row[ "price" ] = float .Parse(sdr[1].ToString());
           row[ "total" ] = num * ( float .Parse(sdr[1].ToString()));
           dt.Rows.Add(row);
  
         }
         sdr.Close();
         conn.Close();
       }
     }
     GridView1.DataSource = dt.DefaultView;
     GridView1.DataBind();
  
   }
   protected void textbox1_TextChanged( object sender, EventArgs e)
   {
     Hashtable ht = (Hashtable)Session[ "shopcar" ];
     if (ht == null ) return ;
     for ( int i = 0; i < GridView1.Rows.Count; i++)
     {
       string id = GridView1.Rows[i].Cells[0].Text.ToString();
       Response.Write(id);
       string num = ((TextBox)GridView1.Rows[i].FindControl( "textbox1" )).Text;
       Response.Write( "  " + num + "<br />" );
       ht[id] = num;
     }
     Session[ "shopcar" ] = ht;
     Bind();
  
   }
   protected void button1_Click( object sender, EventArgs e)
   {
     string id = ((Button)sender).CommandArgument;
     Hashtable ht = (Hashtable)Session[ "shopcar" ];
     if (ht == null ) return ;
     ht.Remove(id);
     Bind();
  
   }
}

制作一个简单的购物车就是这么简单,大家可以按照我的思路进行创作,在此基础上在添加一些功能。

转载于:https://www.cnblogs.com/wanzhongjun/p/6814526.html

  • 1
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
特别说明请注意: 根许多网友反应, using Maticsoft.Functions; 这些代码看不懂 其实Functions 这个dll是我定义常用的函数类,如果需要跟我联系索取http://sql8.net 下面有我的群号, 其中 ArtsShop.Model.Arts_Product _p = new ArtsShop.Model.Arts_Product(); ArtsShop.BLL.Arts_Product p = new ArtsShop.BLL.Arts_Product(); _p = p.GetModel(id); 这是我的商品信息的类,三层结构,这个在用时你们只能换成你们自己的,这些代码完全可以删除, 比如 MyDr[1] = _p.Title; 用来读取商品名的,你们可以改MyDr[1] = dr["productname"].ToString();就行了, AddToCart.aspx页面代码 无标题页 <asp:TextBox ID="TextBox1" runat="server" Text='' Width="44px"> <asp:Label ID="Label1" runat="server" Text=''> 保存 取消 编辑 继续购物 清空购物车 下订单 AddToCart.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 Maticsoft.Functions;public partial class AddToCart : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { int ProID; HttpCookie cookie; bool Tempbl = false; string Tempstr; if (!Page.IsPostBack) { if (!object.Equals(Request.QueryString["id"], null)) { ProID = int.Parse(Request.QueryString["id"]); //创购物车cookie yxy .//sql8.net if (object.Equals(Request.Cookies["ztbscart"], null)) cookie = new HttpCookie("ztbscart"); else cookie = Request.Cookies["ztbscart"]; //判断是否已存在于购物车内 yxy // sql8.net for (int i = 0; i < cookie.Values.Keys.Count; i++) { if (!object.Equals(cookie.Values.Keys[i], null)) { Tempstr = cookie.Values.AllKeys[i].ToString(); if (Tempstr.Trim() != "") { if (ProID == int.Parse(cookie.Values.AllKeys[i])) { Tempbl = true; break; } } } } //不未购买过则加入购物车 yxy //sql8.net if (!Tempbl) cookie.Values.Add(ProID.ToString(), "1"); else { } TimeSpan ts = new TimeSpan(0, 0, 10, 0); cookie.Expires = DateTime.Now + ts; Response.AppendCookie(cookie); } BindGrid(); } } //绑定数据 yxy //sql8.net private void BindGrid() { DataTable MyDt; DataRow MyDr; string str = ""; MyDt = new DataTable(); MyDt.Columns.Add(new DataColumn("id", str.GetType())); MyDt.Columns.Add(new DataColumn("Title", str.GetType())); MyDt.Columns.Add(new DataColumn("Num", str.GetType())); MyDt.Columns.Add(new DataColumn("Price", str.GetType())); MyDt.Columns.Add(new DataColumn("Discount", str.GetType())); MyDt.Columns.Add(new DataColumn("Vipprice", str.GetType())); MyDt.Columns.Add(new DataColumn("Totle", str.GetType())); if (!object.Equals(Request.Cookies["ztbscart"], null)) { HttpCookie cookie = Request.Cookies["ztbscart"]; double Totle; //Response.Write("|" + Request.Cookies["ztbscart"].Values.Keys[1].ToString() + "|"); //Response.End(); for (int i = 0; i < cookie.Values.Keys.Count; i++) { int id; MyDr = MyDt.NewRow(); if (cookie.Values.AllKeys[i] != "" && cookie.Values[i] != "") { id = int.Parse(cookie.Values.AllKeys[i].ToString()); ArtsShop.Model.Arts_Product _p = new ArtsShop.Model.Arts_Product(); ArtsShop.BLL.Arts_Product p = new ArtsShop.BLL.Arts_Product(); _p = p.GetModel(id); MyDr[0] = id; MyDr[1] = _p.Title; MyDr[2] = cookie.Values[i]; MyDr[3] = _p.Price; MyDr[4] = _p.Discount; MyDr[5] = _p.Vipprice1; Totle = double.Parse(MyDr[2].ToString()) * double.Parse(MyDr[5].ToString()); MyDr[6] = Totle; MyDt.Rows.Add(MyDr); } } GridView1.DataSource = MyDt.DefaultView; GridView1.DataBind(); } } protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) { //编辑某行数量 yxy //sql8.net GridView1.EditIndex = e.NewEditIndex; BindGrid(); } protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { //取消更新 yxy //sql8.net GridView1.EditIndex = -1; BindGrid(); } protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) { //更新数量 yxy //sql8.net string num; TextBox tempbx = new TextBox(); Label templb = new Label(); tempbx = (TextBox)(GridView1.Rows[e.RowIndex].Cells[6]).Controls[1]; num = tempbx.Text.ToString(); HttpCookie cookie = new HttpCookie("ztbscart"); for (int i = 0; i < GridView1.Rows.Count; i++) { string id; string tempnum; id = GridView1.Rows[i].Cells[1].Text.ToString(); if (e.RowIndex == i) tempnum = num; else { templb = (Label)(GridView1.Rows[i].Cells[6]).Controls[1]; tempnum = templb.Text.ToString(); } if (tempnum.Trim() == "") tempnum = "0"; //Response.Write("ID:"+id.ToString() + "Num:"+tempnum+":"+i+"");//测试用途 yxy//sql8.net cookie.Values.Add(id, tempnum); } //Response.End(); TimeSpan ts = new TimeSpan(0, 0, 10, 0); cookie.Expires = DateTime.Now + ts; Response.AppendCookie(cookie); GridView1.EditIndex = -1; Message.GoTo("AddToCart.aspx"); } protected void LinkButton4_Click(object sender, EventArgs e) { //继续购物 yxy //sql8.net Message.WebClose(); } protected void LinkButton3_Click(object sender, EventArgs e) { //清空购物车 yxy //sql8.net CheckBox tempcb = new CheckBox(); HttpCookie cookie = new HttpCookie("ztbscart"); Label templb = new Label(); for (int i = 0; i < GridView1.Rows.Count; i++) { tempcb = (CheckBox)(GridView1.Rows[i].Cells[0]).Controls[1]; if (!tempcb.Checked) { string id; string tempnum; id = GridView1.Rows[i].Cells[1].Text.ToString(); templb = (Label)(GridView1.Rows[i].Cells[6]).Controls[1]; tempnum = templb.Text.ToString(); if (tempnum.Trim() == "") tempnum = "0"; //Response.Write("ID:"+id.ToString() + "Num:"+tempnum+":"+i+"");//测试用途 yxy//sql8.net cookie.Values.Add(id, tempnum); } } TimeSpan ts = new TimeSpan(0, 0, 10, 0); cookie.Expires = DateTime.Now + ts; Response.AppendCookie(cookie); Message.GoTo("AddToCart.aspx"); } protected void CheckAll_CheckedChanged(object sender, EventArgs e) { //全选事件 yxy //sql8.net CheckBox tempcb = new CheckBox(); bool tempbl; tempcb = (CheckBox)(GridView1.HeaderRow.Cells[0]).Controls[1]; tempbl = tempcb.Checked; for (int i = 0; i < GridView1.Rows.Count; i++) { tempcb = (CheckBox)(GridView1.Rows[i].Cells[0]).Controls[1]; tempcb.Checked = tempbl; } } } _________________________________________________________________________ 如转载请注明原出处 www.sql8.net
使用: 第1 '================================================= '建立购物车对象,该对象用于直接在程序中调用 '================================================= dim uCart set uCart= new UserCart 第二 建立一个购物车 uCart.CreateCart (可以重复建立,因为里面有IsArray判断。所以建议这句在建立购物车对象后必写) 第三 增加购物车里的商品,在客户端点了某产品后,服务器端处理的ASP文件中接受传过来的产品标志,并访问数据库。分别把AddItem(aID产品标 志如ID,aName产品名称,aPrice1产品价格一,如单价,aPrice2产品价格二如会员价,aPrice3产品价格三如金牌会员价,如果没这么多可以置空 或置0,aCount购买数量,一般是一个,多个的话后面可以用修改函数修改,aImage产品图片地址) 使用方法:aa=uCart.AddItem(aID产品标志如ID,aName产品名称,aPrice1产品价格一,如单价,aPrice2产品价格二如会员价,aPrice3产品价格 三如金牌会员价,如果没这么多可以置空或置0,aCount购买数量,一般是一个,多个的话后面可以用修改函数修改,aImage产品图片地址),返回 true表示成功,false表示失败 第四 增加了以后进如显示页面,就要用到查看购物车 mycart=uCart.ViewCart() For i =LBound(myCart,2) to UBound(myCart,2) if myCart(0,i)"" then myCart(0,i) '获取标号 myCart(1,i) '获取单价 。。。以此类推 end if next 第五 查看了,可以修改购物车,如更改数量等,或是删除其中的 call uCart.ModifItem(mID唯一标志号,mCount产品数量,mFlag-标志 0-添加 1-删除,2-修改 3-清空) '先用给后面参数赋值 修改其中的商品 可以用第四个显示,先接受session的值,然后循环修改 或清空购物车 uCart.RemoveAll() 然后结帐,很简单 myprice=uCart.TPrice() 然后myprice(0)是产品单价的总价格,myprice(1)是产品会员价的总价格,myprice(2)是高级会员的总价格,myprice(3)是产品总数量 将商品装入购物车,这时需要用cookie或session来做一个不同页面间传递的全局变量,也就是说关了浏览器(针对session)或清楚了cookie等原因,本次购物车会消失,就象你今天在商场买了一车的东西,最后没结帐,明天肯定没了,又归位了,当然要有特殊需要保存,可以写数据库!所以这里记录的只需要是该商品的相关信息就可以了,这里我们记录他的 物品ID, 物品单价, 物品名称, 物品数量
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值