Learn ASP.NET MVC, ASP.NET Core, and Design Patterns through our online training programs. Courses conducted by Bipin Joshi on weekends. Read more details here.

Developing a Shopping Cart - Part 2

Introduction

In the previous article we saw how to create a shopping cart using cookies. Continuing the concept further this article will illustrate how to use session variables to create a shopping cart.

Developing a simple product listing page

We will first build a simple web form that lists Products table of Northwind database in a DataGrid.

  1. Create a new web project in VS.NET with C# as the language.
  2. Add a web form called ProductCatalog.aspx to it
  3. Drag and drop a DataGrid control on it.
  4. Write a function called BindGrid() as shown below:
private void BindGrid()
{
SqlDataAdapter da=
new SqlDataAdapter
("select * from products",
@"data source=.\vsdotnet;initial catalog=northwind;user id=sa");
DataSet ds=new DataSet();
da.Fill(ds,"products");
DataGrid1.DataSource=ds;
DataGrid1.DataBind();
}
  1. Call this function in the Page_Load event handler
private void Page_Load(object sender, System.EventArgs e)
{
	if(!Page.IsPostBack)
	{
		BindGrid();
	}
}
  1. Write following code in the SelectedIndexChanged event of the DataGrid.
private void DataGrid1_SelectedIndexChanged
(object sender, System.EventArgs e)
{
ArrayList arr;
if(Session["mycart"]!=null)
{
	arr=(ArrayList)Session["mycart"];
}
else
{
	arr=new ArrayList();
	Session["mycart"]=arr;
}
CShoppingCartItem item=new CShoppingCartItem();
item.ProductID=
int.Parse(DataGrid1.SelectedItem.Cells[1].Text);
item.ProductName=DataGrid1.SelectedItem.Cells[2].Text;
item.UnitPrice=
decimal.Parse(DataGrid1.SelectedItem.Cells[3].Text);
item.Quantity=1;
arr.Add(item);
}

Here, we create an ArrayList for storing the selected products. We check whether we have already stored it in the session or no. If we have already stored then we get hold of the existing session variable else we create a new session variable.

  1. Drag and drop a button control on the web form and write following code in the it's click event handler.
private void Button1_Click
(object sender, System.EventArgs e)
{
Response.Redirect("cart.aspx");
}

Here, we are simply navigating to the cart.aspx page which displays the shopping cart.

Creating the shopping cart web form

  1. Add another web form to the above project called cart.aspx
  2. Create a class called CShoppingCartItem as shown below:
public class CShoppingCartItem
{
private int intProductID;
private string strProductName;
private decimal decUnitPrice;
private int intQuantity;

public int ProductID
{
	get
	{
		return intProductID;
	}
	set
	{
		intProductID=value;
	}
}
public string ProductName
{
	get
	{
		return strProductName;
	}
	set
	{
		strProductName=value;
	}
}
public decimal UnitPrice
{
	get
	{
		return decUnitPrice;
	}
	set
	{
		decUnitPrice=value;
	}
}
public int Quantity
{
	get
	{
		return intQuantity;
	}
	set
	{
		intQuantity=value;
	}
}
}

This class is going to represent one item of the shopping cart.

  1. Drag and drop a DataGrid on the web form.
  2. Create a function called FillCartFromSession() as shown beow:
private void FillCartFromSession()
{
ArrayList items=(ArrayList)Session["mycart"];
DataGrid1.DataSource=items;
DataGrid1.DataBind();
Button1_Click(null,null);
}

Here, we get hold of the ArrayList that we saved in the session previously and then bind the grid with the arraylist.

  1. Drag and drop a button called Recalculate and write following code to its click event handler
private void Button1_Click
(object sender, System.EventArgs e)
{
decimal total=0;
try
{
foreach(DataGridItem dgi in DataGrid1.Items)
{
if(dgi.ItemType==ListItemType.Item 
|| dgi.ItemType==ListItemType.AlternatingItem)
{
TextBox t=(TextBox)dgi.Cells[3].Controls[1];
int quantity=int.Parse(t.Text);
decimal unitprice=Decimal.Parse(dgi.Cells[2].Text);
total=total + (unitprice * quantity);
}
}
}
catch
{
}
lblAmt.Text=total.ToString();
}

This code calculates the total amount of the items selected based on the quantity entered and displays it in a label.

  1. Finally, we will write code to delete items from the cart.
private void DataGrid1_DeleteCommand
(object source, 
System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
ArrayList items=(ArrayList)Session["mycart"];
for(int i=0;i<items.Count;i++)
{
if(((CShoppingCartItem)items[i]).ProductID==
int.Parse(e.Item.Cells[0].Text))
{
items.RemoveAt(i);
break;
}
}
FillCartFromSession();
}

Here, we simply iterate through the ArrayList stored in the session and remove the item based on ProductID.

Code Download

The complete working example is available for download. Please see the link at the top of the article.

Summary

In this article we saw how to use Session variables to store shopping cart. This approach has an advantage as compared to cookie driven cart that you need not worry whether client browser is supporting cookies. On the downside you are putting burden on the server because in default mode Session variables are stored in the memory of the web server. So, this technique is suitable to small to moderately trafficked web sites. In the next article we will see how to store shopping cart in SQL Server database.




Bipin Joshi is a software consultant, trainer, author and a yogi having 21+ years of experience in software development. He conducts online courses in ASP.NET MVC / Core, jQuery, AngularJS, and Design Patterns. He is a published author and has authored or co-authored books for Apress and Wrox press. Having embraced Yoga way of life he also teaches Ajapa Meditation to interested individuals. To know more about him click here.

Get connected : Twitter  Facebook  Google+  LinkedIn

Posted On : 30 Jan 2005



Tags : ASP.NET Web Forms Server Controls