Click here to Skip to main content
15,894,180 members
Articles / Web Development / ASP.NET

Simple Shopping Cart

Rate me:
Please Sign up or sign in to vote.
3.79/5 (32 votes)
31 Dec 2010CPOL2 min read 190.5K   18.2K   32   29
Simple shopping cart with session
ShoppingCart.jpg

Introduction

This is a simple basket or shopping cart, that user can select some goods from list and add them to shopping cart. Also a user can remove or change the count of each good. In this article, I use session for storing the shopping cart user can submit for buying and shopping cart saved in database.

Using the Code

In Web, if you need to have common variable in all pages, you must save in session. Session variables store in server and for each user webserver creates a new session ID and session variables. You can store any object in session. I create a DataTable for storing shopping cart and set it in session variable.

Creating a session is very simple:

C#
Session["variable-name"] = variable-value;

Session variable will remove after session time out (default time is 20 minutes), but if you want to remove a session variable:

C#
Session.Remove("variable-name");

In this project, I store DataTable in session. In Page_Load, if there is session variable it reads and if not, it creates an empty DataTable.

C#
if (Session["basket"] != null)
	///read Basket_DataTable from session if exist
	Basket_DataTable = (DataTable)Session["basket"];
else
{
	//create an empty DataTable and Add some columns to it
	Basket_DataTable = new DataTable();
	Basket_DataTable.Columns.Add("id");
	Basket_DataTable.Columns.Add("name");
	Basket_DataTable.Columns.Add("price");
	Basket_DataTable.Columns.Add("pic");
	Basket_DataTable.Columns.Add("count");
	Basket_DataTable.Columns.Add("total");
}

After this, all changes will be made on Basket_DataTable and finally Basket_DataTable saved in session.

C#
Session["basket"] = Basket_DataTable; 

For adding items to shopping cart, I first search for item in Basket_DataTable and if it not found, item will add to shopping cart:

C#
//search item in DataTable
bool Found = false;
for (int i = 0; i < Basket_DataTable.Rows.Count; i++)
    if (Basket_DataTable.Rows[i][0].ToString() == 
    Request["ID"].ToString())
        Found = true;

In the above code, Request["ID"] is ID of Item.

Before adding Item, I search item ID in database and if it finds item, add to basket.

C#
//add item to DataTable
if (Found == false)
{
    //search item in database
    DataAcess data = new DataAcess();
    string sql = "SELECT * FROM kala where id=" + Request["ID"];
    DataTable ret= data.exe_select(sql);
    //if it found in database add it to basket
    if (ret != null && ret.Rows.Count == 1)
    {
        Basket_DataTable.Rows.Add(new object[] 
        { Request["ID"],ret.Rows[0]["name"].ToString()
                                  ,ret.Rows[0]["price"].ToString(),
                                  ret.Rows[0]["pic"].ToString()
                                 ,"1",ret.Rows[0]["price"].ToString()});
    }
}

For removing items from shopping cart, I add a link in each Item that send item id. To remove I search item and if it is found, it will be removed.

C#
if (Request["DelID"] != null)
{
    //search and remove
    for (int i = 0; i < Basket_DataTable.Rows.Count; i++)
        if (Basket_DataTable.Rows[i][0].ToString() == 
        Request["DelID"].ToString())
            Basket_DataTable.Rows.Remove(Basket_DataTable.Rows[i]);
}

Also I add a TextBox for each item, for item count. User can change item count and click update button and item count will change in DataTable.

C#
for (int i = 0; i < GridView2.Rows.Count; i++)
{
    TextBox Tb=(TextBox) GridView2.Rows[i].FindControl("TextBoxCount");
    Basket_DataTable.Rows[i]["count"] = Tb.Text;
    Basket_DataTable.Rows[i]["total"] = Convert.ToInt32(Tb.Text)*
		Convert.ToInt32(Basket_DataTable.Rows[i]["price"]);
}

I also add some code for saving shopping cart in database, I save item id and item count in database.

C#
DataAcess data = new DataAcess();
for (int i = 0; i < GridView2.Rows.Count; i++)
{
	String ID = GridView2.Rows[i].Cells[0].Text.ToString(); ;
	TextBox Tb = (TextBox)GridView2.Rows[i].FindControl("TextBoxCount");
	string sql = "INSERT INTO Basket (count, id)VALUES ({0}, {1})";
	sql = string.Format(sql, Tb.Text, ID);
	data.exe_cmd(sql);
}

Summary

In this article, I describe a simple shopping cart with session. It is simple but I hope it helps you. Also, you can find a simple and useful class for connecting to database (I don't mention in the article).

Have fun with C# coding.

History

  • 31st December, 2010: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Engineer neyshabur azad univeristy
Iran (Islamic Republic of) Iran (Islamic Republic of)
I had worked as programmer,project manager,web developer for more than 3 years, and have worked on programming personaly for more than 10 years.
I have worked in university as a teacher for 8 years.
my favorite langueges are : VC++,C#,ASP.NET,PHP

Comments and Discussions

 
Suggestion[My vote of 1] Not good Pin
subhadeep.a.mitra30-Mar-12 2:03
subhadeep.a.mitra30-Mar-12 2:03 
GeneralRe: [My vote of 1] Not good Pin
mohammad hajibegloo30-Mar-12 21:52
mohammad hajibegloo30-Mar-12 21:52 
GeneralRe: [My vote of 1] Not good Pin
lida.y28-Aug-12 22:18
lida.y28-Aug-12 22:18 
GeneralMy vote of 5 Pin
asdf1234hn6-Jan-11 21:03
asdf1234hn6-Jan-11 21:03 
GeneralMy vote of 5 Pin
Sunasara Imdadhusen4-Jan-11 23:17
professionalSunasara Imdadhusen4-Jan-11 23:17 
GeneralMy vote of 1 Pin
g0got231-Dec-10 10:45
g0got231-Dec-10 10:45 
RantRe: My vote of 1 Pin
mohammad hajibegloo1-Jan-11 8:10
mohammad hajibegloo1-Jan-11 8:10 
GeneralRe: My vote of 1 Pin
Sunasara Imdadhusen4-Jan-11 23:17
professionalSunasara Imdadhusen4-Jan-11 23:17 
What should be?

sunaSaRa Imdadhusen
+91 99095 44184
+91 02767 284464

General[My vote of 2] Using SQL in UI Pin
Gagan111831-Dec-10 7:13
Gagan111831-Dec-10 7:13 
GeneralMy vote of 1 Pin
Not Active31-Dec-10 7:02
mentorNot Active31-Dec-10 7:02 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.