Answered by:
Shopping cart & Data Access

Question
-
User-394943341 posted
Hi,
I'm in the process of learning asp.net web forms & C# so please bear with me!
I've cannibalized a bit of C# code off the internet (https://code.tutsplus.com/tutorials/build-a-shopping-cart-in-aspnet--net-1663) and I'm struggling to populate & refer to a couple of properties from my data class.
My CartProducts class (not sure where the constructor should include the Desc & Price fields....also tried setting _desc as a fixed value to test things...):
public class CartProducts { private int _prodID; public int ProdID { get { return _prodID; } set { _prodID = value; } } private string _desc; public string Desc { get { return _desc; } set { _desc = value; } //set { _desc = "abcde12"; } //tried hard coding values..... } private decimal _price; public decimal Price { get { return _price; } set { _price = value; } } //constructor for products on customer order form //public CartProducts(int Prod_ID, string cust_acc_prod, decimal smdea_rate1) //{ // _prodID = ProdID; _desc = Desc; _price = Price; //} //constructor for products on customer order form public CartProducts(int _prodID) { _prodID = ProdID; } }
This is the cannibilized code:
public class ShoppingCart { #region Properties public List<CartItem> Items { get; private set; } #endregion #region Implementation // The static constructor is called as soon as the class is loaded into memory public static ShoppingCart GetShoppingCart() { // If the cart is not in the session, create one and put it there if (HttpContext.Current.Session["ASPNETShoppingCart"] == null) { ShoppingCart cart = new ShoppingCart(); cart.Items = new List<CartItem>(); HttpContext.Current.Session["ASPNETShoppingCart"] = cart; } return (ShoppingCart)HttpContext.Current.Session["ASPNETShoppingCart"]; } // A protected constructor ensures that an object can't be created from outside protected ShoppingCart() { } #endregion #region Item Modification Methods /** * AddItem() - Adds an item to the shopping */ public void AddItem(int productId) //add desc & price?? { // Create a new item to add to the cart CartItem newItem = new CartItem(productId); // If this item already exists in our list of items, increase the quantity // Otherwise, add the new item to the list if (Items.Contains(newItem)) { foreach (CartItem item in Items) { if (item.Equals(newItem)) { item.Quantity++; return; } } } else { newItem.Quantity = 1; Items.Add(newItem); } } /** * SetItemQuantity() - Changes the quantity of an item in the cart */ public void SetItemQuantity(int productId, int quantity) { // If we are setting the quantity to 0, remove the item entirely if (quantity == 0) { RemoveItem(productId); return; } // Find the item and update the quantity CartItem updatedItem = new CartItem(productId); foreach (CartItem item in Items) { if (item.Equals(updatedItem)) { item.Quantity = quantity; return; } } } /** * RemoveItem() - Removes an item from the shopping cart */ public void RemoveItem(int productId) { CartItem removedItem = new CartItem(productId); Items.Remove(removedItem); } #endregion #region Reporting Methods /** * GetSubTotal() - returns the total price of all of the items * before tax, shipping, etc. */ public decimal GetSubTotal() { decimal subTotal = 0; foreach (CartItem item in Items) subTotal += item.TotalPrice; return subTotal; } #endregion } /** * The CartItem Class * * Basically a structure for holding item data */ public class CartItem : IEquatable<CartItem> { #region Properties // A place to store the quantity in the cart // This property has an implicit getter and setter. public int Quantity { get; set; } private int _productId; public int ProductId { get { return _productId; } set { // To ensure that the Prod object will be re-created _product = null; _productId = value; } } //https://code.tutsplus.com/tutorials/build-a-shopping-cart-in-aspnet--net-1663 private CartProducts _product = null; public CartProducts Prod { get { // Lazy initialization - the object won't be created until it is needed if (_product == null) { _product = new CartProducts(ProductId); } return _product; } } public int prodid { get { return ProductId; } } string dd = "dfdvjh"; //this works passing a fixed value public string Description { //get { return Prod._smdea_desc; } get { return dd; } } public string desc { //get { return Prod._smdea_desc; } get { return Prod.Desc; } } public decimal UnitPrice { get { return Prod.Price; } } public decimal TotalPrice { get { return UnitPrice * Quantity; } } #endregion // CartItem constructor just needs a productId public CartItem(int productId) { this.ProductId = productId; } /** * Equals() - Needed to implement the IEquatable interface * Tests whether or not this item is equal to the parameter * This method is called by the Contains() method in the List class * We used this Contains() method in the ShoppingCart AddItem() method */ public bool Equals(CartItem item) { return item.ProductId == this.ProductId; } }
I've altered the CartItem class to refer to my CartProducts class and this is where I'm stuck. As you can see I've set a string dd to test the Description value but I'm not sure how I go about obtaining the true CartProducts Desc & Price properties (and where I set them...I'm assumming in my code behind; do I need to alter cart.AddItem method to included Desc & Price??? )
Code behind (the web page displays a list of products with an AddToOrder button for each row):
protected void gvProductsOrder_RowCommand(object sender, GridViewCommandEventArgs e) { // If multiple buttons are used in a GridView control, use the // CommandName property to determine which button was clicked. if (e.CommandName == "AddToOrder") { // Convert the row index stored in the CommandArgument // property to an Integer. int index = Convert.ToInt32(e.CommandArgument); // Retrieve the row that contains the button clicked // by the user from the Rows collection. GridViewRow row = gvProductsOrder.Rows[index]; //gets product id Label lblid = (Label)gvProductsOrder.Rows[index].FindControl("lbl_Prod_ID"); int prodid = Convert.ToInt32(lblid.Text); //gets _cust_acc_prod Label lblcustaccprod = (Label)gvProductsOrder.Rows[index].FindControl("lbl_cust_acc_prod"); string custaccprod = lblcustaccprod.Text; // Create a new ListItem object for the contact in the row. ListItem item = new ListItem(); item.Text = prodid.ToString() + " ~ " + custaccprod + " ~ " + Server.HtmlDecode(row.Cells[2].Text) + " ~ " + Server.HtmlDecode(row.Cells[3].Text); // If the contact is not already in the ListBox, add the ListItem // object to the Items collection of the ListBox control. if (!OrderListBox.Items.Contains(item)) { OrderListBox.Items.Add(item); } //Response.Redirect("ViewCart.aspx"); //add in here the price and description??? ShoppingCart cart = ShoppingCart.GetShoppingCart(); cart.AddItem(prodid);
My markup for the shopping cart (this only currently pulls in the prodid & hard-coded Description:
<asp:GridView runat="server" ID="gvShoppingCart" AutoGenerateColumns="false" EmptyDataText="There is nothing in your shopping cart." GridLines="None" Width="100%" CellPadding="5" ShowFooter="true" DataKeyNames="ProductId" OnRowDataBound="gvShoppingCart_RowDataBound" OnRowCommand="gvShoppingCart_RowCommand"> <%-- <HeaderStyle HorizontalAlign="Left" BackColor="#3D7169" ForeColor="#FFFFFF" /> <FooterStyle HorizontalAlign="Right" BackColor="#6C6B66" ForeColor="#FFFFFF" /> <AlternatingRowStyle BackColor="#F8F8F8" />--%> <Columns> <asp:BoundField DataField="prodid" HeaderText="prodid" /> <asp:BoundField DataField="Description" HeaderText="Description" /> <asp:TemplateField HeaderText="Quantity"> <ItemTemplate> <asp:TextBox runat="server" ID="txtQuantity" Columns="5" Text='<%# Eval("Quantity") %>'></asp:TextBox><br /> <asp:LinkButton runat="server" ID="btnRemove" Text="Remove" CommandName="Remove" CommandArgument='<%# Eval("ProductId") %>' style="font-size:12px;"></asp:LinkButton> </ItemTemplate> </asp:TemplateField> <asp:BoundField DataField="UnitPrice" HeaderText="Price" ItemStyle-HorizontalAlign="Right" HeaderStyle-HorizontalAlign="Right" DataFormatString="{0:C}" /> <asp:BoundField DataField="TotalPrice" HeaderText="Total" ItemStyle-HorizontalAlign="Right" HeaderStyle-HorizontalAlign="Right" DataFormatString="{0:C}" /> </Columns> </asp:GridView>
Thanks in advance for any pointers in the right direction.
Wednesday, July 4, 2018 9:39 AM
Answers
-
User-394943341 posted
resolved.
public void AddItem(int productId, string xdesc) //add desc & price?? { // Create a new item to add to the cart CartItem newItem = new CartItem(productId); newItem.xdesc = xdesc;
public class CartItem : IEquatable<CartItem> { #region Properties // A place to store the quantity in the cart // This property has an implicit getter and setter. public int Quantity { get; set; } public string xdesc { get; set; }
//Response.Redirect("ViewCart.aspx"); //add in here the price and description??? ShoppingCart cart = ShoppingCart.GetShoppingCart(); cart.AddItem(prodid, custaccprod);
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Wednesday, July 4, 2018 11:21 AM