phudq90
phudq90

Reputation: 33

Can't add product to current session ShoppingCart ASP.NET

I'm building a shopping cart with session state. But i've a problem that when i add a product into cart it's seen like creates a new session, not add to current session, so it's only show one last added product.

This is how i organised my site:

Class *App_Code/Cart.cs*

public class Cart
{
DataTable cart = new DataTable();

public Cart()
{
    cart.Columns.Add("id");
    cart.Columns.Add("image");
    cart.Columns.Add("name");
    cart.Columns.Add("price");
    cart.Columns.Add("quantity");
    cart.Columns.Add("total");
}

public DataTable getCart()
{
    return cart;
}

public DataTable addProductToCart(int id, string image, string name, double price)
{
    if (cart.Rows.Count != 0)
    {
        foreach (DataRow row in cart.Rows)
        {
            if (row["id"].ToString().Equals(id.ToString()))
            {
                row["quantity"] = int.Parse(row["quantity"].ToString()) + 1;
                row["total"] = int.Parse(row["total"].ToString()) * price;
                return cart;
            }
        }
    }
        DataRow newrow = cart.NewRow();
        newrow["id"] = id;
        newrow["image"] = image;
        newrow["name"] = name;
        newrow["price"] = price;
        newrow["quantity"] = 1;
        newrow["total"] = price;
        cart.Rows.Add(newrow);
        return cart;
}

And this is the codebehind of ProductDetail.aspx:

public partial class ProductDetail : System.Web.UI.Page
{
    Cart crt;

    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void datalistProductDetail_ItemCommand(object source, DataListCommandEventArgs e)
    {
        switch (e.CommandName)
         {
            case "Add":
                DataListItem item1 = e.Item;
                int id = int.Parse((item1.FindControl("idLabel") as Label).Text);
                string name = (item1.FindControl("nameLabel") as Label).Text;
                double price = double.Parse((item1.FindControl("priceLabel") as Label).Text);
                string image = ((item1.FindControl("img") as Image).ImageUrl.Replace("~/images/sp/", ""));
                crt.addProductToCart(id, image, name, price);
                setCartToSession(crt);
                break;
        }
    }
    protected void setCartToSession(Cart crt)
    {
        Session["Cart"] = crt;
    }
}

And this is the ViewCart.aspx:

public partial class ViewCart: System.Web.UI.Page
{
    Cart crt;

    protected void Page_Load(object sender, EventArgs e)
    {
        gh = getGioHangFromSession();
        refresh_gridviewCart();
    }

    protected void refresh_gridviewCart()
    {
        gridviewCart.DataSource = crt.getCart();
        gridviewCart.DataKeyNames = new string[] { "id" };
        gridviewCart.DataBind();
    }

    protected Cart getCartFromSession()
    {
        if (Session["Cart"] == null)
        {
            return new Cart();
        }
        else return (Session["Cart"] as Cart);
     }

    protected void setCartToSession(Cart crt)
    {
        Session["Cart"] = crt;
    }
}

Upvotes: 1

Views: 3203

Answers (3)

jasvant yadav
jasvant yadav

Reputation: 1

Best way to add to cart product in cart using asp.net

         DataSet ds = null;
    if (Session["sCart"] == null)
    {
        ds = new DataSet();
        DataTable dt = new DataTable();
        dt.Columns.Add(new DataColumn("Product_Code", typeof(System.Int32)));
        dt.Columns.Add(new DataColumn("Product_Name", typeof(System.String)));
        dt.Columns.Add(new DataColumn("Qty", typeof(System.Int32)));
        dt.Columns.Add(new DataColumn("Price", typeof(System.Int32)));
        dt.Columns.Add(new DataColumn("Total_Price", typeof(System.Int32)));
        ds.Tables.Add(dt);
        Session["sCart"] = ds;
    }
    else
    {
        ds = (DataSet)Session["sCart"];
    }
    DataRow row = ds.Tables[0].NewRow();
    row["Product_Code"] = lblpcode.Text;
    row["Product_Name"] = lblpname.Text;
    row["Qty"] = TextBox1.Text;
    row["Price"] = lblprice.Text;
    row["Total_Price"] = Convert.ToInt32(TextBox1.Text) * Convert.ToInt32(lblprice.Text);


    ds.Tables[0].Rows.Add(row);
    Response.Redirect("mycart.aspx");

Upvotes: 0

phudq90
phudq90

Reputation: 33

public partial class ProductDetail : System.Web.UI.Page
{
Cart crt = new Cart();

protected void Page_Load(object sender, EventArgs e)
{

}
protected void datalistProductDetail_ItemCommand(object source, DataListCommandEventArgs e)
{
    switch (e.CommandName)
     {
        case "Add":
            DataListItem item1 = e.Item;
            int id = int.Parse((item1.FindControl("idLabel") as Label).Text);
            string name = (item1.FindControl("nameLabel") as Label).Text;
            double price = double.Parse((item1.FindControl("priceLabel") as Label).Text);
            string image = ((item1.FindControl("img") as Image).ImageUrl.Replace("~/images/sp/", ""));
            crt.addProductToCart(id, image, name, price);
            setCartToSession(crt);
            break;
    }
}
protected void setCartToSession(Cart crt)
{
    List<Cart> dt = new List<Cart>();
    if (Session["cart"] != null)
    {
        dt.AddRange((List<Cart>)Session["Cart"]);
    }
    dt.Add(crt);
    Session["Cart"] = dt;
}
}

Upvotes: 1

Pankaj
Pankaj

Reputation: 10105

I'm building a shopping cart with session state. But i've a problem that when i add a product into cart it's seen like creates a new session, not add to current session, so it's only show one last added product.

protected void setCartToSession(Cart crt)
{
    List<Cart> dt = new List<Cart>();
    if (Session["cart"] != null)
    {
        dt.AddRange((List<Cart>)Session["Cart"]);
    }
    dt.Add(crt);
    Session["Cart"] = dt;
}

Upvotes: 1

Related Questions