1(818)262-8552
Or Email
contact@invertedsoftware.com

A classic shopping cart including source code in C#


By Gal Ratner

The shopping cart is the most common component used to today.
Almost every website has a shopping cart in one form or another. Even this one.
It usually includes some sort of a database to hold inventory and track sales, maybe an email generator to notify customers and merchants about new transactions.
Finally, a secure payment gateway in order to process credit cart transactions.
There are many "off the shelf" items available today, however, for some business needs, nothing works best as a custom cart.
A cart that was written along with the rest of the site and using the same design, navigation menu and shares a database with the rest of site's features.
In this article I am going to focus on the actual cart component.
To be exact, the same object that is in charge of keeping products in memory, calculating total, shipping charges, and taxes and finally, is able to display itself on the screen in a shape of a list of all the products you have added to your shopping cart.
The heart of the system is a generic Dictionary. It holds as its value, a custom CartItemInfo object and as its key, the ProductID as shows in your database.
I have based this example on the Pet Shop 4.0 store from Microsoft.
Unlike the Microsoft version, we are not going to use a custom cart provider but, a session object instead.
CartDataHelper will be used as our data layer and will be able to select the current product from the database using SQLHelper, again from the Pet Shop.

The Files:

Cart.cs- Holds the main Dictionary along with its utility methods.
CartItemInfo.cs- Holds all the attributes for a singe product.
CartDataHelper.cs- Is the data layer and can communicate with the database via SQLHelper
SQLHelper.cs- provided by Microsoft and encapsulates best practices for ADO.NET.
ShoppingCartViewerWebUserControl.ascx- displays the cart on any page.
ShoppingCart.aspx- Displays the cart and enable to edit and remove products.

Adding a product to the cart will look like this:

if (Session["ShoppingCart"] != null) shoppingCart = (Cart)Session["ShoppingCart"];
else shoppingCart = new Cart();
shoppingCart.Add(ProductID); // This is an integer
Session["ShoppingCart"] = shoppingCart;
Response.Redirect("ShoppingCart.aspx");


The database will look like:



I hope you find this code helpful the next time you need a shopping cart.

Note: This code is provided As Is and with No Warrenty

Download The Code Here



About Us | Contact Us | Standards of Business Conduct | Employment
InvertedSoftware.com All rights reserved