Hi i am new to asp.net and have followed a tutorial in creating a shopping cart and thats working fine. I would like to modify it to produce the products from my database rather than get static products from a class which it does now.

Sorry for the masses of code but just thought i would put it in so you can understand.

If anyone could help that would be great.

Many Thanks in advance

Heres my code

The page which displays the products:

<div class="contentBox">
        <h1 class="heading">Place and Rrder</h1>
			<div>Shoes - <asp:LinkButton runat="server" ID="btnAddShirt" OnClick="btnAddShoes_Click">Add To Cart</asp:LinkButton></div>
			<div>Shirt - <asp:LinkButton runat="server" ID="btnAddShorts" OnClick="btnAddShirt_Click">Add To Cart</asp:LinkButton></div>
			<div>Pants - <asp:LinkButton runat="server" ID="btnAddShoes" OnClick="btnAddPants_Click">Add To Cart</asp:LinkButton></div>
			<a href="ViewCart.aspx">View Cart</a>
    </div>

and the code behind:

	protected void btnAddShoes_Click(object sender, EventArgs e) {
		// Add product 1 to the shopping cart
		ShoppingCart.Instance.AddItem(1);

		// Redirect the user to view their shopping cart
		Response.Redirect("ViewCart.aspx");
	}

	protected void btnAddShirt_Click(object sender, EventArgs e) {
		ShoppingCart.Instance.AddItem(2);
		Response.Redirect("ViewCart.aspx");
	}

	protected void btnAddPants_Click(object sender, EventArgs e) {
		ShoppingCart.Instance.AddItem(3);
		Response.Redirect("ViewCart.aspx");
	}

}

The view cart page:

<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="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>
			<br />
			<asp:Button runat="server" ID="btnUpdateCart" Text="Update Cart" OnClick="btnUpdateCart_Click" />

and the code behind

 protected void Page_Load(object sender, EventArgs e)
    {
		if (!IsPostBack)
			BindData();
    }

	protected void BindData() {
		gvShoppingCart.DataSource = ShoppingCart.Instance.Items;
		gvShoppingCart.DataBind();
	}

	protected void gvShoppingCart_RowDataBound(object sender, GridViewRowEventArgs e) {
		if (e.Row.RowType == DataControlRowType.Footer) {
			e.Row.Cells[3].Text = "Total: " + ShoppingCart.Instance.GetSubTotal().ToString("C");
		}
	}

	/**
	 * This is the method that responds to the Remove button's click event
	 */
	protected void gvShoppingCart_RowCommand(object sender, GridViewCommandEventArgs e) {
		if (e.CommandName == "Remove") {
			int productId = Convert.ToInt32(e.CommandArgument);
			ShoppingCart.Instance.RemoveItem(productId);
		}

		// We now have to re-setup the data so that the GridView doesn't keep
		// displaying the old data
		BindData();
	}

	protected void btnUpdateCart_Click(object sender, EventArgs e) {
		foreach (GridViewRow row in gvShoppingCart.Rows) {
			if (row.RowType == DataControlRowType.DataRow) {
				try {
					// Get the productId from the GridView's datakeys
					int productId = Convert.ToInt32(gvShoppingCart.DataKeys[row.RowIndex].Value);
					// Find the quantity TextBox and retrieve the value
					int quantity = int.Parse(((TextBox)row.Cells[1].FindControl("txtQuantity")).Text);
					ShoppingCart.Instance.SetItemQuantity(productId, quantity);
				} catch (FormatException) { }
			}
		}

		BindData();
	}

The shopping cart Class:

public class ShoppingCart {
	#region Properties
	
	public List<CartItem> Items { get; private set; }
	
	#endregion

	#region Singleton Implementation

	// Readonly properties can only be set in initialization or in a constructor
	public static readonly ShoppingCart Instance;
	// The static constructor is called as soon as the class is loaded into memory
	static ShoppingCart() {
		// If the cart is not in the session, create one and put it there
		// Otherwise, get it from the session
		if (HttpContext.Current.Session["ASPNETShoppingCart"] == null) {
			Instance = new ShoppingCart();
			Instance.Items = new List<CartItem>();
			HttpContext.Current.Session["ASPNETShoppingCart"] = Instance;
		} else {
			Instance = (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) {
		// 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 products class:

public class Product
{

	public int Id { get; set; }
	public decimal Price { get; set; }
	public string Description { get; set; }

	public Product(int id)
	{
		this.Id = id;
		switch (id) {
			case 1:
				this.Price = 19.95m;
				this.Description = "Shoes";
				break;
			case 2:
				this.Price = 9.95m;
				this.Description = "Shirt";
				break;
			case 3:
				this.Price = 14.95m;
				this.Description = "Pants";
				break;
		}
	}

}

and the Cart Items class:

public class CartItem : IEquatable<CartItem> {
	#region Properties

	// A place to store the quantity in the cart
	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;
		}
	}

	private Product _product = null;
	public Product Prod {
		get {
			// Lazy initialization - the object won't be created until it is needed
			if (_product == null) {
				_product = new Product(ProductId);
			}
			return _product;
		}
	}

	public string Description {
		get { return Prod.Description; }
	}

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

	public bool Equals(CartItem item) {
		return item.ProductId == this.ProductId;
	}
}

Anyone?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.