繁体   English   中英

GridView for ASP.NET C#中的购物车

[英]GridView for Shopping Cart in ASP.NET C#

我已经制作了一个简单的购物车,但是已经完成了,但是问题是,当有人将商品添加到购物车中时,如果该商品再次添加到购物车中,然后又将其添加为新产品,我需要对其进行更新产品(如果已经存在)。 任何帮助??? 此代码写在购物车查看页面的页面加载中

DataTable dtCart = (DataTable)Session["sessiondtCart"];

            GridView1.DataSource = dtCart;
            GridView1.DataBind();    

            int total = 0;

            for (int i = 0; i < GridView1.Rows.Count; i++)
            {
                total = total + int.Parse(dtCart.Rows[i]["PRODUCT_AMOUNT"].ToString());
            }
            lblTotalAmount.Text = total.ToString();

在购物车中添加商品的代码

protected void lnkBtnReadyToServeAdd_Click(object sender, EventArgs e)
        {
            DataTable dtCart = (DataTable)Session["sessiondtCart"];
            dtCart.Rows.Add(lblProductName.Text, lblProductPrice.Text, txtQuantity.Text, imgk1.ImageUrl, int.Parse(lblProductPrice.Text) * int.Parse(txtQuantity.Text));
            Session["sessiondtCart"] = dtCart;

        }

我希望您能够提出一个非常基本的实现。

protected void lnkBtnReadyToServeAdd_Click(object sender, EventArgs e)
{
    DataTable dtCart = (DataTable)Session["sessiondtCart"];
    foreach(DataRow row in dtCart.Rows)
    {
        if(row["ProductName"] == lblProductName.Text) //check if already exists
        {
            //now we know we need to increment the quantity, because it's already in the cart
            int quantity = row["TotalPrice"] / int.Parse(lblProductPrice.Text);
            row["TotalPrice"] = quantity + int.Parse(txtQuantity.Text);
        }
        else
        {
            //now we know the item wasn't in the cart, so we need to add it
            dtCart.Rows.Add(lblProductName.Text, lblProductPrice.Text, txtQuantity.Text, imgk1.ImageUrl, int.Parse(lblProductPrice.Text) * int.Parse(txtQuantity.Text));
        }
    }

    Session["sessiondtCart"] = dtCart;
}

这里有一些注意事项。 您似乎并没有为您的产品使用ID,因此我们被迫依靠唯一的产品名称。 这不是很好,通常最好为每个产品分配一个唯一的ID。

您不应将价格存储在购物车中。 您应该只存储ProductId和Quantity。 当您想知道价格时,应该在数据库中查找价格是多少。 否则,有人可以轻松地将lblProductPrice设置为0并免费获得产品。 这也将简化更新数量的逻辑,因为您不必再​​除以总价即可获取现有数量。

最后,您使用整数作为价格。 快速演示可能很好。 但是,如果您的产品价格为3.99美元,该怎么办? 您应该使用小数或双精度数而不是整数。 数量可能是整数,因为大多数时候您不会有分数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM