Skip to main content

Building an ASP.NET Shopping Cart Using DataTables Article

By Zak Ruvalcaba
Step 3: Building the Add to Cart Functionality

Now that the structure of the DataTable has been completely built, we’ll want to begin to add to the cart the specific items that the user selects from the drop down menu. Again, to do this, we simply construct new rows and add them to the appropriate position within the DataTable cart. To construct the Add to Cart functionality, add the code below:

Sub AddToCart(s As Object, e As EventArgs)  
    objDT = Session("Cart")  
    Dim Product = ddlProducts.SelectedItem.Text  
    objDR = objDT.NewRow  
    objDR("Quantity") = txtQuantity.Text  
    objDR("Product") = ddlProducts.SelectedItem.Text  
    objDR("Cost") = Decimal.Parse(ddlProducts.SelectedItem.Value)  
    Session("Cart") = objDT  
    dg.DataSource = objDT  
End Sub

You’ll remember that the Button control had the onClick event that called the AddToCart() subroutine. This subroutine contains all the code that’s necessary to retrieve an existing cart from the Session object if it exists, add new items to the cart, place the cart back into the session, and finally, bind to the DataGrid.

As I mentioned, the first two lines of code retrieve the cart from the session if it exists, and retrieve the product selected from the drop down menu. As you have already created a new instance of the DataRow class, you can create the new rows for the specific columns within the DataTable.

You’ll notice that we set the Quantity column equal to the value of the quantity text box control, and set the Product column equal to the text value of the drop down menu selection. We then convert the value of the drop down menu, which is cost, into a decimal value for the cost column. Finally, we add the new row to the DataTable, add the DataTable to the Session, or overwrite it if it already exists, and bind the DataTable to the DataGrid.

Test what you have so far in the browser. It should work fine, except for one problem. You’ll see that if you select an item, add it to the cart, and then select the same item again, rather than adding the sum of the old quantity with the new quantity, it just creates a new row. You can fix this problem by modifying the AddToCart() subroutine. Just below the code where you retrieve the item from the drop down menu, add the following loop to check within the DataTable for an existing product:

Dim blnMatch As Boolean = False  
For Each objDR In objDT.Rows  
    If objDR("Product") = Product Then  
         objDR("Quantity") += txtQuantity.Text  
         blnMatch = True  
         Exit For  
    End If  

Now wrap the new code that adds a new row within a conditional statement.

If Not blnMatch Then  
    objDR = objDT.NewRow  
    objDR("Quantity") = Int32.Parse(txtQuantity.Text)  
    objDR("Product") = ddlProducts.SelectedItem.Text  
    objDR("Cost") = Decimal.Parse(ddlProducts.SelectedItem.Value)  
End If

Basically, a new row will only be created if the product is not found within the cart. If it is found, however, it will simply adjust the quantity by whatever the user places into the quantity textbox control.

Step 4: Keeping the Order Total

The next step will be to build the function that keeps a running total of the cost of the items within the cart. This will be used to present the user with a working total as they add and remove items in the cart. You can add this functionality using the code below:

Function GetItemTotal() As Decimal  
    Dim intCounter As Integer  
    Dim decRunningTotal As Decimal  
    For intCounter = 0 To objDT.Rows.Count -- 1  
         objDR = objDT.Rows(intCounter)  
         decRunningTotal += (objDR("Cost") * objDR("Quantity"))  
    Return decRunningTotal  
End Function

You can see that this function simply loops through the rows in the DataTable, multiplies the quantity column by the cost column, and returns the result. The first step involves defining the functon. As you want to return a decimal value, make sure you define the function as a decimal. Next, we’ll create two new variables: one as an integer and one as a decimal. Next, you loop through the rows within the DataTable and multiply the cost column for a specific row by the quantity for that row, and store it within the decRunningTotal variable. Finally, we’ll return the value.

The last step will be to write the value of the function into the label control. Add the following line to the end of the btnAddToCart subroutine — this effectively writes the cost into the label control:

lblTotal.Text = "$" & GetItemTotal()

Save your work and run it in a browser. This time, as you add items to the cart, a total is presented within the label control. Fantastic! Now, the last part we’ll discuss involves removing items from the cart.

Step 5: Removing Items from the Cart

Now that a working model of the shopping cart has been constructed, we’ll want to add the next bit of functionality: removing items from the cart. Obviously you can see the importance of this: you want users to be able to add and remove any and all items to or from the shopping cart as required. Add the functionality for removing items from the cart using the following subroutine:

Sub Delete_Item(s As Object, e As DataGridCommandEventArgs)  
    objDT = Session("Cart")  
    Session("Cart") = objDT  
    dg.DataSource = objDT  
    lblTotal.Text = "$" & GetItemTotal()  
End Sub

This subroutine, which we’ll associate with the DataGrid in a minute, simply dumps the contents of the session into a new DataTable object, deletes the specific row that a user clicked, and then places the revised DataTable back into the Session variable for storage. Finally we re-bind to the DataGrid and update the total by calling the GetItemTotal() function.

You’ll want to note that one of the parameters being passed into the subroutine is that of the DataGridCommandEventArgs. Without this parameter, we wouldn’t be able to determine which item within the DataGrid the user selected.

The last step will be to modify the DataGrid. You will need to add a new button column, as well as a new event, to call the Delete_Item subroutine. The new DataGrid should resemble the following code:

<asp:DataGrid id=dg runat="server"  ondeletecommand="Delete_Item">  
<asp:buttoncolumn buttontype="LinkButton"  
commandname="Delete" text="Remove Item" />  

Save your work and run it in the browser. This time you can add products and remove them freely!


As you have seen, building your own shopping cart isn’t very difficult. The great thing about building your own cart is that it is completely customizable — and you don’t have to spend hundreds of dollars for an extension suite that you end up having to learn anyway.

Go to page: 1 | 2

Involved in the Web since 1995, Zak is founder of and advisor to Module Media, a full service design and development firm in San Diego. He is author of �The Ten Minute Guide to Dreamweaver 4� and �Dreamweaver MX Unleashed�, and SitePoint's own Build Your Own ASP.NET Website Using C# and VB.NET.

Integromat Tower Ad