Search code examples
asp.netvb.netshopping-cart

how do i get purchased items to a gridview in a shopping cart?


Hey I recently created a shopping cart but I'm having problems sorting the purchased items into a gridview. this is my cart class:

Public Class Cart
    Private dt As DataTable = New DataTable()

    Public Sub New()
        dt.Columns.Add(New DataColumn("Product ID"))
        dt.Columns.Add(New DataColumn("Quantity"))
        dt.PrimaryKey = New DataColumn() {dt.Columns("Product ID")}
    End Sub

    Public Sub AddToCart(ByVal prd_id As Integer, ByVal quantity As Integer)
        Dim dr As DataRow = dt.NewRow()
        dr("Product ID") = prd_id
        dr("Quantity") = quantity
        dt.Rows.Add(dr)
    End Sub

    Public Sub RemoveFromCart(ByVal prd_id As Integer)
        Dim dr As DataRow = dt.Rows.Find(prd_id)
        dt.Rows.Remove(dr)
    End Sub

    Public Function GetCart() As DataTable
        Return dt
    End Function
End Class

This is the button function:

If Session("Customer_ID") <> Nothing Then
    Dim userCart As Cart = CType(Session("shoppingCart"), Cart)
    Dim qty As Integer = txtqty.text
    Dim pid As Integer = lblid.text
    userCart.AddToCart(pID, qty)
Else 
    Response.Redirect("User_Login.aspx")
End If

When I try to run the code I get an error saying that ("Object reference not set to an instance of an object.") please help I've completely ran out of ideas. how can i fix this?


Solution

  • The Session Key of "shoppingCart" has a value Nothing, so when you try to call the AddToCart function from your userCart instance you receive this error. You must ensure that Session("shoppingCart") is not nothing. If it is you should create it or perform the logic you wish to perform in that scenario. Note that Sessions will time out after a client is inactive for a certain amount of time (configurable in the Web.config file), so this is a very real scenario.

        Dim userCart As Cart = Nothing
    
        If Not Session("shoppingCart") Is Nothing Then
    
            userCart = CType(Session("shoppingCart"), Cart)
    
        Else
    
            userCart = New Cart
    
        End If
    
        userCart.AddToCart(pID, qty)
    

    Don't forget to save your cart to the Session!

        Session("shoppingCart") = userCart