隨便在網上找個購物車的例子看看就明白了!
public partial class Cart : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
CartBind();
}
}
private void CartBind()
{
DataTable dtCart = null;
if (Session["User"] != null)
{
if (Session["Cart"] != null)
{
dtCart = Session["Cart"] as DataTable;
}
else
{
Response.Write("<script>alert('您購物車裏沒有信息,請購買物品!');window.location='BookList.aspx';</script>");
return;
}
}
else
{
Response.Write("<script>alert('請登陸!');window.location='Login.aspx';</script>");
return;
}
if (dtCart.Rows.Count != 0)
{
this.gvCart.DataSource = dtCart;
this.gvCart.DataBind();
Operation(Session["Cart"] as DataTable);
}
else
{
Response.Write("<script>alert('您購物車裏沒有信息,請購買物品!');window.location='BookList.aspx';</script>");
}
}
protected string GetImageURL(object obj)
{
if (File.Exists(Server.MapPath(obj.ToString())))
{
return obj.ToString();
}
return "~/BookCovers/default.jpg";
}
private void Operation(DataTable dtSource)
{
decimal result = 0;
foreach (DataRow row in dtSource.Rows)
{
result += decimal.Parse(row["BookPrice"].ToString())
* int.Parse(row["BookNumber"].ToString());
}
this.labSalary.Text = result.ToString();
}
protected void imgbtnSalary_Click(object sender, ImageClickEventArgs e)
{
}
protected void gvCart_RowEditing(object sender, GridViewEditEventArgs e)
{
this.gvCart.EditIndex = e.NewEditIndex;
CartBind();
}
protected void gvCart_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
TextBox txtNumber = this.gvCart.Rows[e.RowIndex].
FindControl("txtBookNumber") as TextBox;
Response.Write(txtNumber.Text);
DataTable dtSource = Session["Cart"] as DataTable;
dtSource.Rows[e.RowIndex]["BookNumber"] = int.Parse(txtNumber.Text.Trim());
Session["Cart"] = dtSource;
this.gvCart.EditIndex = -1;
CartBind();
}
protected void gvCart_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
this.gvCart.EditIndex = -1;
CartBind();
}
protected void gvCart_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
DataTable dtSource = Session["Cart"] as DataTable;
dtSource.Rows[e.RowIndex].Delete();
Session["Cart"] = dtSource;
CartBind();
}