Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | ASP.NET 2.0 Tutorials | Web Services | How Do I...? | Class Browser | WPF Quick Starts | Advertise with Us
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Nevron Chart
Search :       Advanced Search »
Home » VB.NET » 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 :
Page Views : 111290
Downloads : 5341
Rating :
 Rate it
Level : Intermediate
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
shoppingCart1.zip
 
 
DevExpress Free UI Controls
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

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.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
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 Communication Foundation
Appl ication Developmen, software Developer/ project lead with 9 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 applications / sites with SQL/Oracle as back-end. Currently he  is focusing more on Silverlight, WCF & WPF development. He had worked on payment gateway implementation. He is experienced in Insurance, Supply Chain management, Trading, Real-Estate & currently Legacy modernization domain.
Apart from this he has implemented on CMMi L3 for organization and has good understanding of process. He has also involved in consulting activities like Architecture Review, Project Plan, HLD, LLD, Risk Management etc....
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.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Comments
could not get update link to work by garrett On July 6, 2006

Hi,

I just downloaded your sample code for the javascript cart for vb.net which I think is a great idea, but I could not get the update function to work.  I am having to use 1.1 .Net but I dont think that would cause a problem on this example.  Please let me know if you have any ideas.

Thanks,

Garrett

Reply | Email | Modify 
Re: could not get update link to work by Munir On July 10, 2006

Hi,

First of all thankx for downloading shopping cart article.
Initially i do not think that there should be any problem, but you can look in to browser setting if it support for javascript, you can debugg this article line by line.
There should not be any problem since i have not received single comment from the rest all downloaders.



Regards,
>>Munnamax

Reply | Email | Modify 
Re: could not get update link to work by Munir On January 29, 2007

Hi,

I thank you for downloading shopping cart and making this so popular, please check if your browser support for javascript, other wise there should not be any problem, or for dibugging you can check putting javascript:alert(''); it shoudl work.

Enjoy easy coding!

>>Munnamax

Reply | Email | Modify 
shopping cart by lilin On July 22, 2006
hi i tried your shopping cart codes but when i try to view them in ie browser i don't see the datafields inside.Do i have to key in myself or ?
Reply | Email | Modify 
Re: shopping cart by Munir On July 24, 2006

Hi,

You should check with your database table if it has records in it, for me i am fetching records from "products" table of SQL SERVER.


Regards,
Munnamax

Reply | Email | Modify 
help by amara On October 15, 2006

sir,

 

i requesting to u for give me a suggestion regarding .net

 

wt is the features .net rather than java?

 

iam studying mca final year plz guidence to me

 

and give replay to my mail id amarareddy@gmail.com

Reply | Email | Modify 
Add to Cart by Star On November 28, 2006

Hi

I am trying to use your code in a project for school, the Add to Cart doesn't work! I am using ASP.net version 2.0

Reply | Email | Modify 
Re: Add to Cart by Munir On December 5, 2006

Hi,

The structure of asp.net 2.0 is differing than the 1.0, obiously it will give you error, i will be writing new article on this in comming months. But it should work provided that.

 

Thanks
>>Munnamax

Reply | Email | Modify 
Shopping Cart ASP.net / VB.Net - the next stage by Dave On December 31, 2006

Hi Munnamax

 

I have integrated and added to the code to make a .NET 2.0 cart work with a MasterPage.

 

I am now a little stumped as to how to pull the data from the cells into a payment gateway - I've been able to do this with the total value but not the other elements. Of course I also need to find a way of updating the database with the cell values.

 

Could you point me in the right direction?

 

Thanks

 

Happy New Year

 

I have now managed this (of sorts) but I guess there must be a more efficient way to do it - and this method does limit the amount of rows (unless you want to code forever and ever...

 

if vTotalRows > 3 Then

'start JavaScript

Dim GetValues As String = "<script language='JavaScript'>" & _

"var table= document.getElementById('Table1'); " & _

"var totalrows = table.rows.length; " & _

"var i = (totalrows - 3) ; " & _

"var nID = new Array(i); " & _

"nID[0] = table.rows[2].cells[0].innerText; " & _

"var vQty1 = document.getElementById('ctl00_txt0').value ; " & _

"if (i > 1) { " & _

"nID[1] = table.rows[3].cells[0].innerText; " & _

"var vQty2 = document.getElementById('ctl00_txt1').value ; " & _

"}" & _

"else { " & _

"nID[1] = ''; " & _

"var vQty2 = '' ;" & _

"}" & _

"if (i > 2) { " & _

"nID[2] = table.rows[4].cells[0].innerText; " & _

"var vQty3 = document.getElementById('ctl00_txt2').value ; " & _

"}" & _

"else { " & _

"nID[2] = '' ;" & _

"var vQty3 = '' ;" & _

"} " & _

"if (i > 3) { " & _

"nID[3] = table.rows[5].cells[0]; " & _

"var vQty4 = document.getElementById('ctl00_txt3').value ; " & _

"} " & _

"else { " & _

"nID[3] = '' ; " & _

"var vQty4 = '' ; " & _

"}" & _

"if (i > 4) { " & _

"nID[4] = table.rows[6].cells[0]; " & _

"var vQty5 = document.getElementById('ctl00_txt4').value ; " & _

"} " & _

"else { " & _

"nID[4] = ''; " & _

"var vQty5 = '' ; " & _

"} " & _

"if (i > 5) { " & _

"nID[5] = table.rows[7].cells[0]; " & _

"var vQty6 = document.getElementById('ctl00_txt5').value ; " & _

"} " & _

"else { " & _

"nID[5] = '' ; " & _

"var vQty6 = '' ; " & _

"}" & _

"if (i > 6 ) { " & _

"nID[6] = table.rows[8].cells[0]; " & _

"var vQty7 = document.getElementById('ctl00_txt6').value ; " & _

"} " & _

"else { " & _

"nID[6] = '' ; " & _

"var vQty7 = '' ; " & _

"}" & _

"document.getElementById('Label1').innerText = nID[0] ; " & _

"document.getElementById('Label2').innerText = nID[1] ; " & _

"document.getElementById('Label3').innerText = nID[2] ; " & _

"document.getElementById('Label4').innerText = vQty1 ; " & _

"document.getElementById('Label5').innerText = vQty2 ; " & _

"document.getElementById('Label6').innerText = vQty3 ; " & _

"</script>"

'end JavaScript

GetValues = GetValues.Replace("Table1", Table1.ClientID).Replace("Label1", Label1.ClientID)

GetValues = GetValues.Replace("Label2", Label2.ClientID).Replace("Label3", Label3.ClientID).Replace("Label4", Label4.ClientID)

GetValues = GetValues.Replace("Label5", Label5.ClientID).Replace("Label6", Label6.ClientID)

Page.ClientScript.RegisterStartupScript(Me.GetType(), "GetValues", GetValues)

Else

Label1.Text = "Table is empty!"

End If

Reply | Email | Modify 
S i am having doubt in gateway integration by Rahul On November 23, 2007
good notes for me
Reply | Email | Modify 
model view of shopping product inventry in vb.net, my kannan_its@ymail.com by kannan On September 20, 2008
please anybdy know the this concept then send the my mail or any way
Reply | Email | Modify 
to update/edit quantity of the product that user added in cart .. by rupa On September 21, 2008
Hi, I a student that i am developing a project on shopping cart,I have to bind textbox control to display the quantity of the product that a user added to cart so that user can update the quanity of products, previously added if they want.How can I do like,please give idea then I will be ever gratefull to you.
Reply | Email | Modify 
What to DO After that User Has Made His Cart by raghav On January 23, 2009
Hi, Good Explanantion BUt What To Do After that As u have wriiten >>> In next one of the session I will present code snippet for integrating with authorized.net payment gateway. Ok I have made my cart and has n number of items in that .What to do after that .How He Will PAy what after that.....Please Explain
Reply | Email | Modify 
How to add payment gateway??? by ashita On February 21, 2009
Thank you,this code is wonderful.It is simple as well.But, please send me code for making payments at er.atewari1@gmail.com Thanks & Regards, Ashita
Reply | Email | Modify 
asp.net 2.0 by Michael On March 3, 2009
Is there a good example asp.net shopping cart out there?
Reply | Email | Modify 
Latest version of shopping cart by Nubia On March 24, 2009
Do you have a version of shopping cart that is compatible with Visual Studio 2005, SQL Server 2005, and ASP.NET 2.0/3.5 coded in VB, if so please send to nlevon@cox.net
Reply | Email | Modify 
VB.NET Shopping cart(ASP.NET) by Kamil On May 11, 2009

Thanks for script.

Also one of VB.NET shopping cart: http://advantshop.com

Reply | Email | Modify 
thx by funY On September 13, 2009
thx
Reply | Email | Modify 
I wanna know about Shopping Cart Projects in Asp.net using vb.net codes by divya On December 27, 2009
hello friends, i wanna know about the Shopping Cart projects in asp.net using vb.net codings pls help me in this and send me some easy understanding projects to my e-mail id: pappuskolpoyachu@ymail.com PLS HELP !!!
Reply | Email | Modify 
Very usefull by guna On January 9, 2010
this is very useful for web page developer 
Reply | Email | Modify 
same consept different funtion by ohood On March 6, 2010

Hi
i have shopping cart case but it seems different than this solution
Can u help me in it plz

Reply | Email | Modify 
feedback by inder On May 19, 2010
nice website
Reply | Email | Modify 
VB Script request by Nick On August 16, 2010
Thanks for providing us with your example but may you please upload the one using VB Script instead of Java Script.Thanks
Reply | Email | Modify 
Could not able to Reterive Image from the Database by narendar On September 7, 2010
Hi,

Protected Function bindData()
        Dim con As New SqlConnection(ConfigurationSettings.AppSettings("connectionstring"))
        Dim objDA As SqlDataAdapter
        Dim myRow As SqlDataReader
        Dim comd As New SqlCommand("SELECT * FROM products", con)
        con.Open()
        myRow = comd.ExecuteReader()
        Dim strRowGen As String = ""
        While myRow.Read()
            strRowGen = strRowGen & "<TR>"
            strRowGen = strRowGen & "<TD>" & myRow.GetValue(1) & "</TD>"
            strRowGen = strRowGen & "<TD>" & myRow.GetValue(4) & "</TD>"
            strRowGen = strRowGen & "<TD>" & myRow.GetValue(5) & "</TD>"
            strRowGen = strRowGen & "<TD><a href='#' onclick=""javascript:document.Form1.action='ShoppingPage.aspx?Actn=Add&itemId=" & myRow.GetValue(0) & "';document.Form1.submit();"">Add To Cart</TD>"
            strRowGen = strRowGen & "</TR>"
            cellshoping.InnerHtml = strRowGen
        End While
    End Function

In the above Code,  The Image type of Data is not able to Retreive & the related code is given below :

strRowGen = strRowGen & "<TD>" & myRow.GetValue(5) & "</TD>"

Get the Error :
Converting a Byte Datatype into String Datatype is not possible.

Pls if anybody knows the Solution for the above Problem, Pls send the Solution

Thx
Reply | Email | Modify 
shopping cart by pawan On January 21, 2011
Really very nice thanks a lot
Reply | Email | Modify 
Nevron Chart
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.