簡體   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