C#
  Home arrow C# arrow Page 2 - Data Handling with a Shopping Cart/PayPal ...
ASP Free Forums 
.NET  
ASP  
ASP Code  
ASP.NET  
ASP.NET Code  
BrainDump  
C#  
Code Examples  
Database  
Database Code  
IIS  
Microsoft Access  
MS SQL Server  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
ASP Web Hosting  
ASP.NET Web Hosting 
Mobile Linux 
App Generation ROI 
Windows Web Hosting
 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
C#

Data Handling with a Shopping Cart/PayPal System
By: Tann San
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 5
    2006-06-20

    Table of Contents:
  • Data Handling with a Shopping Cart/PayPal System
  • The Shopping Basket
  • A further note on security
  • Payment

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Data Handling with a Shopping Cart/PayPal System - The Shopping Basket


    (Page 2 of 4 )

    The shopping basket is used to store products that the customer selects from the product listing by clicking the "Add to basket" button next to each product.  It's fine to store the basket in Session state as in a full shop this data may be discarded at any moment by the customer deciding to leave your site, or maybe just from them emptying their basket.  You could choose to store their basket choices in a database for several reasons, such as for market research purposes to identify who's looking at what, and to identify trends in buying habits.  Another reason may be to present them with "Last time you were here you looked at these items ..." type displays.  That would require you to have a method to distinguish between customers.  Two commonly used techniques involve storing a cookie on their system with a unique ID to identify them on future visits, or basing it off their login ID if you implement customer logins later.

    The basket also uses the createProductDT() function to create its initial empty DataTable.  For this demonstration we're going to use the same table structure, but you may wish to refine your basket by removing some of the columns.  In most situations you will only need to store the ID and quantity of each product, since you could easily look up the actual product details based on its ID.

    Each time a product is added to the basket via the product listing, its "Add to basket" button fires an OnServerClick event:

      protected void shopBuy_OnServerClick(object source, EventArgs
    e)
         {     
            int index = ((GridViewRow)((HtmlInputButton)
    source).Parent.NamingContainer).RowIndex;   
            addToBasket(Convert.ToInt32(gvProducts.DataKeys
    [index].Value));
         } 

      protected void addToBasket(int productID)
         {
            DataTable dtBasket = getBasketDt();

            // Loop through the basket and check if this item already
    exists
            bool found = false;
            for(int i = 0; i < dtBasket.Rows.Count; i++)
               { 
                  if(Convert.ToInt32(dtBasket.Rows[i]["id"]) ==
    productID)
                     {
                        // increment the quantity and mark as found
                        dtBasket.Rows[i]["quantity"] =
    Convert.ToInt32(dtBasket.Rows[i]["quantity"]) + 1;
                        found = true;

                        // break out of the for loop as we have
    already found the item at this point
                        break;
                     } 
               }

            // If the item is not found then add it as a new
    row                  
            if(!found)
               {           
                  DataTable dtProducts = getProductsDt
    ();                       
                  DataRow drProduct = dtProducts.Rows.Find
    (productID);

                  // Now we've got the data we need from our
    datasource we can add a new row to the basket   
                  DataRow newRow = dtBasket.NewRow();
                  newRow["id"] = drProduct["id"];
                  newRow["name"] = drProduct["name"];
                  newRow["price"] = drProduct["price"];
                  newRow["quantity"] = 1;

                  dtBasket.Rows.Add(newRow);
               }

            // Store the newly updated basket back in the Session
            Session["dtBasket"] = dtBasket;

            // Update the basket i.e. re-bind it
            updateShopBasket();
         }  

    We catch this using the shopBuy_OnServerClick() function, which identities which row the button belongs to, gets the associated product ID and then uses that to call addToBasket().  Inside that we check the basket for the product ID.  If it already exists in the basket, we just increment its quantity, and if it doesn't, we add it as a new row.  Finally we re-bind the basket to its updated DataSource.


    The basket, like the product GridView, uses TemplateColumns, so we can have a quantity text box in each row.  This gives the customer an easy way to update the number of each item that they desire.  Once they've changed the value, they click the "Update Quantities" button below the basket.  This fires an OnServerClick event which gets caught by shopUpdateBasketQuantities
    _OnServerClick().  This is similar to the addToBasket() function in that we have to locate the product in the basket and then update its quantity.  It differs in that we have to be careful when checking the data that has been retrieved from the text box, as you never know what someone might stick in there to confuse the system.  Here's a snippet of the function that handles this checking:

      // Read the data from the Quantity Text Box
      HtmlInputText itQuant = (HtmlInputText)row.FindControl("itProductQuantity");

      // Try and convert the value to an int
      try

         {

            int quant = Convert.ToInt32(itQuant.Value);

         
            /*
             * If the value converted to an Int successfully we still
    need to check
             * that its not a minus number, otherwise we might end up
    owing the customer money!
             */ 
            if(quant > 0)
               {
                  drProduct["quantity"] = quant;     
               }
            else
               {
                  drProduct.Delete();
               }   
         }
      catch
         { 
            // If we cant convert it to an Int then just leave it as
    it was i.e. make no changes
         }

    Say for example someone sticks -100 in as the quantity, you may end up owing them money!  Okay so you probably wouldn't have to actually pay them, but depending on how your payment system is set up, it may pose a problem. For this reason we wrap the integer parsing in a try/catch clause, so that if it can't be parsed we just leave the value as it originally was. After that we check the quantity to make sure that it is greater than zero. If it's less than or equal to zero then we remove the row. Finally, after all the products in the basket have been checked and had their quantities amended, we store the basket and update the display.

    The final key component of the basket is the updateShopBasket() function:

      private void updateShopBasket()
         {  
            gvBasket.DataSource = getBasketDt();
            gvBasket.DataBind();                    

            ibEmptyBasket.Visible = ibUpdateBasketQuantities.Visible
             = ibBasketCheckout.Visible = gvBasket.Rows.Count > 0; 
         } 

    This grabs a copy of the basket out of the Session state, which in turn will create the Session basket if it doesn't already exist, and then binds the GridView. Its final purpose is to hide or show the three basket buttons, as there is no need to show them if the basket is empty.

    More C# Articles
    More By Tann San


       · I'm open to...
       · hey, nice work i must say!My problem is that even though i am directed to a page...
       · are both the pages on the same server and under the same domain name? if their not...
       · I can't run this proj plz tell me
     

    C# ARTICLES

    - Working with Dates and Times in C#
    - Generics, Dictionaries, and More
    - More About Generics
    - Working with C# Collections
    - Generics
    - C# and XML
    - Pointers and Arrays in C#
    - C# 3.0 Extension Methods
    - Overloading Operators in C#
    - Iterators and Nullable Types
    - Patterns and Iterators in C#
    - C# Exceptions
    - Methods in C#
    - Delegates and Events in C#
    - Advanced C#

     
    Best Practices for Windows Vista Migration Presentation
    Dell and Microsoft recently held a series of face-to-face seminars entitled, &qu....

     
    Creating a Culture for Code Reuse
    If you oversee development teams you know that like it or not proprietary and ex....

     
    Keys to Web Application Acceleration: Advances in Delivery Systems
    Accelerate Web apps by up to 5x. Ensure significantly faster access to the Web a....

     
    Optimizing Application Monitoring
    Tired of finding out from your customers that you're offline? This white paper e....

     
    Solaris to Solaris Migration -- Migrating applications from Sun SPARC to Dell PowerEdge R900
    This comprehensive Migration Guide reviews the approach that Principled Technolo....

     




    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 5 hosted by Hostway
    Stay green...Green IT