harron harron - 2 months ago 22
ASP.NET (C#) Question

GridView for Shopping Cart in ASP.NET C#

I have made a simple shopping cart, I have completed it but the problem is when someone add an item to the cart it adds, and if that item again added to the cart then it add it as a new product, I need it to update the product if it already exists.
any help???
this code is written in page load of Cart View Page

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


the code for adding items in the cart

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;

}

Answer

A very basic implementation I would have expected you to be able to come up with.

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

Quite a few notes here. You don't appear to be using an ID for your products, so instead we're forced to rely on the product name being unique. That's not very good, it's usually best to assign each product a unique ID.

You should not store prices in the cart. You should just store the ProductId and the Quantity. When you want to know the price, you should look up in the database what the price is. Otherwise, someone could easily manipulate lblProductPrice to be 0 and get the products for free. It would also simplify the logic for updating the quantity, as you'd no longer have to divide the total price to get the existing quantity.

And lastly, you're using ints for your prices. That might be fine for a quick demo. But what if your product price is $3.99? You should use a decimal or a double instead of an integer. Quantity is probably fine as an int, since most of the time you won't have fractional quantities.