Blue Theme Orange Theme Green Theme Red Theme
 
ASP.NET Web Hosting – Click Here
Home | Forums | ASP.NET 2.0 Tutorials | Web Services | How Do I...? | Class Browser | Videos | Beginners
 | Consulting  
Submit an Article 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
New MS SQL 2008 Available - DiscountASP.NET
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » Internet and Web » Shopping Cart in ASP.NET using VB.NET

Shopping Cart in ASP.NET using VB.NET

Shopping Cart using ASP.Net, VB.Net and SQL server, very light weight small complete application. which uses dynamic HTML Rows and columns generation, i have covered add to cart, update item, delete item, continue shopping method using collection

Author Rank:
Technologies: .NET 1.0/1.1, ASP.NET 1.0,Visual Basic .NET
Total downloads : 2666
Total page views :  56043
Rating :
 3.83/5
This article has been rated :  6 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
shoppingCart1.zip
 
ArticleAd
Become a Sponsor



Before explaining code in detail let me give some knowledge power of HTTPSessionState class, since I have used Add/Remove method of HTTPSessionState class.

HTTPSessionState class Provides access to session-state values as well as session-level settings and lifetime management methods.

  • Method -> Adds a new item to session state.
  • Remove -> Delete an item from session state collection

There could be many method to make shopping cart.

  1. Fully database driven
  2. Collection based

Here I am discussing collection based shopping cart, question is why collection based?

Answer to this question is just to minimize load of the database from storing every activity of cart in the database.

Our aim is to hold product id and quantity in the collection, and while displaying the cart content list all the related data, based on product id from the table.

Updating Cart quantity in the cart is also in the collection which is achieved by using Javascript.

Note: On every link form is submitted using JavaScript and every action is maintained in ShoppingPage.aspx.vb in short Add To cart, Delete, Update etc.

In the entire shopping cart we have following pages:

  1. ShoppingPage.aspx and it's code behind page (Display product list).
  2. ShoppingCart.aspx and it's code behind page (Display cart content).

I will go through the major functionality on by one one each of above page

1. ShoppingPage.aspx

bindData() 

Get the product list in SqlDataReader, it iterate through the product list and  add rows to the table control, in one of the cell it has "Add To Cart" link.

<ahref='#'onclick=""javascript:document.Form1.action='ShoppingPage.aspx?Actn=Add&itemId=" & myRow.GetValue(0) & "';document.Form1.submit();"">Add To Cart</TD>"

In short submits form using javascript with Querystring Parameter Actn=Add and respective itemId from the row.
 
Since same page is acting as controlling page also, so each and every action is taken care on this page, let us have a look at "Add To Cart" functionality code snippet as below:
 
Private Sub AddToSession(ByVal strProduct As String, ByVal intQty As Integer)
     If Not Session(strProduct) Is Nothing Then
          Session.Add(strProduct, CInt(Session(strProduct)) + intQty)
     Else
          Session.Add(strProduct, intQty)
     End If
End Sub

Above code checks if the item is not present in the session, at first time it adds item id / product id with quantity 1 in the session, next time when same product / item is added to the cart it check if product id present if found update quantity + one.

Update Product

Private Sub updateCart(ByVal strProduct As String, ByVal qty As Integer)

     If Not Session(strProduct) Is Nothing Then

         Session.Add(strProduct, CInt(qty))

     End If

End Sub

Above function is just to update cart product with quantity added in the textbox.
 
Delete Product

To remove product from the list, Remove() method of collection is used when Actn=Del & delItemId is passed from the querystring.

Session.Remove(delId)
 
The entire code for above all Action handling goes as below:

Dim strQty As Integer

Dim proId As String

Dim delId As String

delId = Request.QueryString("delItemId")

proId = Request.QueryString("itemId")

'---- Following portion act as controller where code is written as

'---- per the action from the request of the pages like Add To Cart,

'---- Update Cart & Delete Cart

strQty = 1

If Request.QueryString("Actn") <> "" Then

      If Request.QueryString("Actn").Equals("Add") Then

          If Request.QueryString("itemId") <> "" Then

               AddToSession(proId, strQty)

               Response.Redirect("./ShoppingCart.aspx")

          End If

      ElseIf Request.QueryString("Actn").Equals("Del") Then

           If Request.QueryString("delItemId") <> "" Then

                 Session.Remove(delId)

                 Response.Redirect("./ShoppingCart.aspx")

           End If

       ElseIf Request.QueryString("Actn").Equals("Update") Then

            If Request.QueryString("itemUpId") <> "" And Request.QueryString("quantity") <> "" Then

                  If IsNumeric(Request.QueryString("itemUpId")) Then

                        updateCart(Request.QueryString("itemUpId"), Request.QueryString("quantity"))

                        Response.Redirect("./ShoppingCart.aspx")

                    Else

                        Response.Redirect("./ShoppingCart.aspx")

                    End If

            End If

      End If

End If

Now we will have a look at ShoppingCart.aspx as below:

On this page I have following JavaScript function to take care of update function to which quantity and product Id / Item id parameters are supplied.

Function upThis(ByVal qty, ByVal upItemId)
{
      var strUrl="./ShoppingPage.aspx?Actn=Update&quantity='+qty+'&itemUpId='+upItemId";
      document.location.href = strUrl
}

On this page I have a table.

<TABLE id="Table1" width="100%" align="center" borderColor="black" cellSpacing="0" cellPadding="1" border="1" runat="server">

where table Header row is generated with following heading:

  • Product Name
  • Quantity
  • UnitPrice
  • Amount
  • Action

On this page we check Session.Count() and fetch product detail using following query:

SELECT * FROM products WHERE ProductId=" & Session.Keys(intI)

to Session.Keys(intI) we will be having item id / product id.
 
To above table with id="Table1" is added with dynamic row and each row has four cells.

The second row is added with some of the empty rows and Cart Total.

Entire code on this page goes as:

If Not Page.IsPostBack Then
     Dim intI As Integer
     Dim strSql As String
     Dim conn As New SqlConnection(ConfigurationSettings.AppSettings("connectionstring"))
     Dim cmd As SqlCommand
     'Put user code to initialize the page here
     Dim i As Integer
     Dim j As Integer
     Dim row As HtmlTableRow
     Dim strTotal As Double = 0
     For intI = 0 To Convert.ToInt16(Session.Count() - 1)
          'Get the number of rows and columns selected by the user. 
          Dim numrows As Integer = Convert.ToInt16(Session.Count())
          Dim numcells As Integer = 4
          strSql = "SELECT * FROM products WHERE ProductId=" & Session.Keys(intI)
          cmd = New SqlCommand(strSql, conn)
          If conn.State = ConnectionState.Closed Then
                conn.Open()
          End If
          showCart = cmd.ExecuteReader()
          'Dim cell As HtmlTableCell
          Dim cell1 As New HtmlTableCell
          Dim cell2 As New HtmlTableCell
          Dim cell3 As New HtmlTableCell
          Dim cellAmount As New HtmlTableCell
          Dim cellAction As New HtmlTableCell
          If showCart.Read() Then
              ' Iterate through the rows.
              ' Create a new row and add it to the Rows collection.
              row = New HtmlTableRow
              ' Provide a different background color for alternating rows.
              If (intI Mod 2) = 1 Then
              row.BgColor = "Gainsboro"
              End If
              ' Iterate through the cells of a row.
              cell1.Controls.Add(New LiteralControl(showCart.GetValue(1)))
              cell2.Controls.Add(New LiteralControl("<input type='text' name=txt" & intI & " value=" & Session(intI)
              & " maxlength='2' size='2'>&nbsp;<A href='#' onclick=""javascript:upThis(document.Form1.txt" & intI &
              ".value," & showCart.GetValue(0) & ");"">Update</A>"))
              cell3.Controls.Add(New LiteralControl("$" & FormatNumber(showCart.GetValue(5), 0)))
              cellAmount.Controls.Add(New LiteralControl("$" & FormatNumber(CDbl(showCart.GetValue(5)) *
              CDbl
    (Session(intI)), 0)))
              cellAction.Controls.Add(New LiteralControl("<a href='shoppingpage.aspx?Actn=Del&delItemId=" &   
              showCart.GetValue(0) & "'>Delete<A/>"))
              row.Cells.Insert(0, cell1)
              row.Cells.Insert(1, cell2)
              row.Cells.Insert(2, cell3)
              row.Cells.Insert(3, cellAmount)
              row.Cells.Insert(4, cellAction)
              Table1.Rows.Add(row)
              ' summing amount of all the products added in the cart content
              strTotal = strTotal + FormatNumber(CDbl(showCart.GetValue(5)) * CDbl(Session(intI)), 0)
          Else
              'do nothing
          End If
          ' closing recordset 
          showCart.Close()
     Next
     ' cell declaratopm for adding rowTotal
     Dim rowTotal As New HtmlTableRow
     Dim cellEmpty1 As New HtmlTableCell
     Dim cellEmpty2 As New HtmlTableCell
     Dim cellEmpty3 As New HtmlTableCell
     Dim celllTotalHeader As New HtmlTableCell
     Dim cellTotal As New HtmlTableCell
     'Creating seperate cell as literal controll
     cellEmpty1.Controls.Add(New LiteralControl("&nbsp"))
     cellEmpty2.Controls.Add(New LiteralControl("&nbsp"))
     cellEmpty3.Controls.Add(New LiteralControl("&nbsp"))
     celllTotalHeader.Controls.Add(New LiteralControl("Cart Total:$"))
     cellTotal.Controls.Add(New LiteralControl(strTotal))
     ' Adding number of cells to the row
     rowTotal.Cells.Insert(0, cellEmpty1)
     rowTotal.Cells.Insert(1, cellEmpty2)
     rowTotal.Cells.Insert(2, celllTotalHeader)
     rowTotal.Cells.Insert(3, cellTotal)
     rowTotal.Cells.Insert(4, cellEmpty3)
     rowTotal.BgColor = "Gainsboro"
     ' Adding new row
     Table1.Rows.Add(rowTotal)
End If

The above shoppingcart can be extended with one more intermediate stage as instead of having Add to cart functionality on first page we can product detail page to which product images/photos can be shown with more info and we can have "Add To Cart" functionality on the same page.

Another topic related with the shoppingcart to be discussed is: Payment Gateway.

One can add billing and shipping page with cart Total Amount and one can send to this information's to the payment gateways.

I have worked for code integration with following gateways:

  1. Authorized.net
  2. Verysign
  3. Worldpay
  4. YourPay
  5. Paypal

In next one of the session I will present code snippet for integrating with authorized.net payment gateway.


Login to add your contents and source code to this article
 [Top] Rate this article
 About the author
 
Munir Shaikh
Munir is MCP in Microsoft .NET Framework 3.5, Windows Gommunication Foundation
Appl ication Developmen, software Developer/ project lead with 8 Yrs development experience who works on IT projects mainly for Microsoft and some open source technologies. Most of these projects have been intranet based web sites connected to a SQL database. He has focused on Asp.Net, C#, vb.net and SQL Server development. He had worked on payment gateway implementation. He is experienced in Insurance, Supply Chain management, Trading, Real-Estate & currently Legacy moderanization domain.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.