用GridView制作购物小车
aspx源代码如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="MyShoppingCart.aspx.cs" Inherits="MyShoppingCart" %>
<!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>
<form id="form1" runat="server">
<div align=center>
<table width=60%>
<tr>
<td colspan="3">
<asp:GridView ID="gvCart" runat="server" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None" Font-Size="Smaller" Width="513px">
<FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<Columns>
<asp:TemplateField FooterText="del" HeaderText="删除">
<ItemTemplate>
<asp:CheckBox ID="cbdel" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ProName" HeaderText="商品名称" />
<asp:BoundField DataField="unitPrice" HeaderText="单价" />
<asp:TemplateField HeaderText="数量">
<ItemTemplate>
<asp:TextBox ID="CountTb" runat="server" Width="60px" Text='<%# Eval("ProdCount") %>'></asp:TextBox>
<asp:RangeValidator ID="RangeValidator1" runat="server" ControlToValidate="CountTb"
ErrorMessage="*" MaximumValue="100" MinimumValue="1" Type="Integer"></asp:RangeValidator>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="total" HeaderText="小计(元)" />
</Columns>
<SelectedRowStyle BackColor="#C5BBAF" ForeColor="#333333" Font-Bold="True" />
<PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#1C5E55" Font-Bold="False" Font-Names="宋体" Font-Size="11pt" ForeColor="White" HorizontalAlign="Center" VerticalAlign="Middle" />
<AlternatingRowStyle BackColor="White" />
<RowStyle BackColor="#E3EAEB" Wrap="False" />
<EditRowStyle BackColor="#7C6F57" />
</asp:GridView>
</td>
</tr>
<tr>
<td style="width: 100px">
</td>
<td style="width: 100px">
</td>
<td style="width: 100px">
</td>
</tr>
<tr>
<td style="width: 100px; text-align: center;">
<asp:Button ID="updateBtn" runat="server" Text="更新我的购物车" OnClick="updateBtn_Click" /></td>
<td style="width: 150px; text-align: center;" >
<asp:Button ID="CheckOut" runat="server" Text="结算" OnClick="CheckOut_Click" />
<input id="Button1" type="button" value="继续购物" onclick="javascript:window.close()" /></td>
<td style="width: 100px">
<asp:Label ID="Label1" runat="server" ForeColor="Maroon"></asp:Label></td>
</tr>
</table>
</div>
</form>
</body>
</html>
后台代码如下:
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;
public partial class MyShoppingCart : System.Web.UI.Page
{
private string addProId;
private string mode;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["username"] == null)
{
Response.Write("<script>alert('请先登录!')</script>");
Response.Write("<script>window.close()</script>");
}
if (!IsPostBack)
{
addProId = Request.QueryString["ID"];
mode = Request.QueryString["Mode"];
UpdateShoppingCart();
}
}
private void CreateCartTable() //创建购物车
{
DataSet ds = new DataSet();
DataTable newDT = new DataTable("CartTable");
ds.Tables.Add(newDT);
DataColumn newDC;
newDC = new DataColumn("proID", 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("total", System.Type.GetType("System.Double"));
ds.Tables["CartTable"].Columns.Add(newDC);
newDC = new DataColumn("IsDeleted", System.Type.GetType("System.Boolean"));
newDC.DefaultValue = false;
ds.Tables["CartTable"].Columns.Add(newDC);
Session["myCartTable"] = newDT;
gvCart.DataSource = ds.Tables["CartTable"].DefaultView;
gvCart.DataBind();
}
private void UpdateShoppingCart()
{
if (Session["myCartTable"] == null)
{
CreateCartTable();
//调用函数CreateCartTable( )新建一个DataTable
}
WriteShoppingCart();
}
private void WriteShoppingCart()
{
DataTable nowTable = (DataTable)Session["myCartTable"];
if (mode != "view") //检查是否是直接查看购物车,如果直接查看,就不再写MYCARTTABLE
{
bool hasone = false;
int nowProdID;
int i;
for (i = 0; i < nowTable.Rows.Count && !hasone; i++)
{
nowProdID = int.Parse(nowTable.Rows[i]["proID"].ToString());
if (nowProdID == int.Parse(addProId))
{
hasone = true;
}
}
if (hasone)
{
//如果已有该商品,则 hasone=true,更改该数据行
DataRow oldDR = nowTable.Rows[i];
oldDR["ProdCount"] = Int32.Parse(oldDR["ProdCount"].ToString()) + 1;
oldDR["total"] = Int32.Parse(oldDR["ProdCount"].ToString()) * Double.Parse(oldDR["unitPrice"].ToString());
}
else
{
//如果没有该商品,在表中新加如一行.
double unitp;
MyData data = new MyData(MapPath(".") + @"\App_Data\0791idc.mdb");
string strSQL = "select * from [product] where [articleid]=" + addProId + "";
DataTable dt = data.readData(strSQL);
DataRow newDR = nowTable.NewRow();
newDR["proID"] = addProId;
newDR["ProName"] = dt.Rows[0]["title"].ToString();
unitp = Double.Parse(dt.Rows[0]["price"].ToString());
newDR["unitPrice"] = unitp;
newDR["total"] = unitp;
//第一次读库,所以总价格和单价是一样的.
nowTable.Rows.Add(newDR);
}
}
gvCart.DataSource = nowTable.DefaultView;
gvCart.DataBind();
Session["myCartTable"] = nowTable;
//重新保存更新过的DataTable
}
private void Caculator()
{
if (Session["myCartTable"] != null) //购物车是否为空
{
Double TotalPri = 0;
DataTable nowTable = (DataTable)Session["myCartTable"];
if (nowTable.Rows.Count > 0) //返回购物车中是否有货物
{
for (int h = 0; h <= nowTable.Rows.Count - 1; h++)
{
TotalPri = TotalPri + Int32.Parse(nowTable.Rows[h]["total"].ToString());
}
Label1.Text = "总计: " + TotalPri.ToString() + " 元";
}
} //if
}
private void Update()
{
DataTable nowTable2 = (DataTable)Session["myCartTable"];
for (int i = 0; i <= this.gvCart.Rows.Count - 1; i++)
{
TextBox CountText = (TextBox)this.gvCart.Rows[i].Cells[4].FindControl("CountTb");
CheckBox ProductIDCheck = (CheckBox)this.gvCart.Rows[i].Cells[0].FindControl("cbdel");
nowTable2.Rows[i]["ProdCount"] = Int32.Parse(CountText.Text);
nowTable2.Rows[i]["total"] = Int32.Parse(nowTable2.Rows[i]["ProdCount"].ToString()) * Double.Parse(nowTable2.Rows[i]["unitPrice"].ToString());
if (ProductIDCheck.Checked)
{
nowTable2.Rows[i][5] = true;
//添加删除标记
}
}
DataRow[] foundRows = nowTable2.Select("IsDeleted=true");
for (int m = 0; m < foundRows.Length; m++)
{
foundRows[m].Delete();
}
gvCart.DataSource = nowTable2.DefaultView;
gvCart.DataBind();
Session["myCartTable"] = nowTable2;
Caculator();
}
protected void updateBtn_Click(object sender, EventArgs e)
{
Update();
}
protected void CheckOut_Click(object sender, EventArgs e)
{
Update();
Response.Redirect("order_check.aspx");
}
}
浙公网安备 33010602011771号