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();
}
}

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

长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号





    联系我们

    欢迎来到TinyMind。

    关于TinyMind的内容或商务合作、网站建议,举报不良信息等均可联系我们。

    TinyMind客服邮箱:support@tinymind.net.cn