我正在使用VB後端在asp.net中構建一個非常簡單的購物車,但我遇到了代碼問題。當我運行我的應用程序並嘗試將產品添加到購物車時,我收到一條錯誤消息。ASP.NET購物車
Object reference not set to an instance of an object.
描述:執行當前Web請求期間發生未處理的異常。請查看堆棧跟蹤以獲取有關該錯誤的更多信息以及源代碼的位置。
異常詳細信息:System.NullReferenceException:未將對象引用設置爲對象的實例。
源錯誤:
Line 27: Dim blnMatch As Boolean = False
Line 28:
Line 29: For Each Me.objDR In objDT.Rows
Line 30: If objDR("StockItemName") = Product Then
Line 31: objDR("Quantity") += txtQuantity.Text
我不知道爲什麼它是這樣做的,並希望也許有人會來看看,並提供了一些建議嗎?我已經檢查了我的代碼,但是我找不到任何錯誤,但是我會採取任何指導,您可能對此有所瞭解。
這是我的代碼。
Shoppingcart.aspx
<asp:DropDownList id="ddlProducts" runat="server">
襪子 褲子 襯衫 帽
數量:
總:
Shoppingcart.aspx.vb 進口System.Data 部分公共類購物車 繼承System.Web.UI.Page
Dim objDT As System.Data.DataTable
Dim objDR As System.Data.DataRow
Private Sub Page_Load(ByVal s As Object, ByVal e As EventArgs)
If Not IsPostBack Then
makeCart()
End If
End Sub
'Mark Cart function
Function makeCart()
objDT = CType(Session("Cart"), DataTable)
objDT.Columns.Add("StockID", GetType(Integer))
objDT.Columns("StockID").AutoIncrement = True
objDT.Columns("StockID").AutoIncrementSeed = 1
objDT.Columns.Add("StockItemName", GetType(String))
objDT.Columns.Add("StockItemValue", GetType(Decimal))
Session("Cart") = objDT
End Function
'This is for adding items to the shopping cart.
Sub AddToCart(ByVal s As Object, ByVal e As EventArgs)
objDT = Session("Cart")
Dim Product As String = ddlProducts.SelectedItem.Text
Dim blnMatch As Boolean = False
For Each Me.objDR In objDT.Rows
If objDR("StockItemName") = Product Then
objDR("Quantity") += txtQuantity.Text
blnMatch = True
Exit For
End If
Next
If Not blnMatch Then
objDR = objDT.NewRow
objDR("Quantity") = txtQuantity.Text
objDR("StockItemName") = ddlProducts.SelectedItem.Text
objDR("StockItemValue") = Decimal.Parse(ddlProducts.SelectedItem.Value)
objDT.Rows.Add(objDR)
Session("Cart") = objDT
End If
dg.DataSource = objDT
dg.DataBind()
End Sub
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("StockItemValue") * objDR("Quantity"))
Next
Return decRunningTotal
End Function
Sub Delete_Item(ByVal s As Object, ByVal e As DataGridCommandEventArgs)
objDT = Session("Cart")
objDT.Rows(e.Item.ItemIndex).Delete()
Session("Cart") = objDT
dg.DataSource = objDT
dg.DataBind()
lblTotal.Text = "$" & GetItemTotal()
End Sub
末級
是在會話中的車真的不空? – 2011-02-07 16:06:14