使用按钮在VB.net中增加变量

时间:2013-02-28 16:11:17

标签: asp.net sql vb.net

我正在尝试按下按钮来增加变量。它只增加一次。似乎它在重新加载页面时迷路了。

我正在使用以下代码:

Dim ItemSelect As New ArrayList()
Dim Quantities As New ArrayList()
Dim itemQtyOrdered As Integer

Public Sub ShtickDataList_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.ListViewCommandEventArgs) Handles ShtickDataList.ItemCommand

    If e.CommandName = "ViewCart" Then
        Response.Redirect("~/ShoppingCart.aspx")
    End If

    If e.CommandName = "addToCart" Then
        Dim itemQuantity As DropDownList = e.Item.FindControl("QuantityDropDown")
        itemQtyOrdered = itemQuantity.SelectedValue
        ItemSelect.Add(e.CommandArgument)
        Quantities.Add(itemQtyOrdered)

        Session("itemInCart") = ItemSelect
        Session("quantities") = Quantities

        viewInvoice()
    End If

End Sub

Protected Sub viewInvoice()

    Dim itemSelected As ArrayList = DirectCast(Session("itemInCart"), ArrayList)
    Dim QuantityofItem As ArrayList = DirectCast(Session("quantities"), ArrayList)
    Dim conn As SqlConnection
    Dim comm As SqlCommand
    Dim reader As SqlDataReader
    Dim purimConnection2 As String = ConfigurationManager.ConnectionStrings("Purim").ConnectionString
    conn = New SqlConnection(purimConnection2)

    comm = New SqlCommand("SELECT ProductName FROM Products WHERE ProductID = @ProductID", conn)

    Dim i As Integer
    For i = 0 To ItemSelect.Count - 1
        comm.Parameters.Add("@ProductID", Data.SqlDbType.Int)
        comm.Parameters("@ProductID").Value = ItemSelect(i)
    Next

    Try
        conn.Open()
        reader = comm.ExecuteReader()
        ViewCartlink.Text = "View Cart: (" & ItemSelect.Count & ")"
    Finally
        conn.Close()
    End Try
End Sub

1 个答案:

答案 0 :(得分:1)

啊,您可能指的是ItemSelectQuantities列表。您需要在Session中查找它们,并且只有在它们不在Session中时才创建它们。我在VB.NET上生锈了,所以这是C#版本。在Page_Load

ItemSelect = (ArrayList)Session["itemInCart"];
if (ItemSelect == null)
{
  ItemSelect = new ArrayList();
  Session["itemInCart"] = ItemSelect;
}

Quantities相同。

另外,viewInvoice方法中的循环错误。对于ItemSelect列表中的多个项目,您将添加具有相同名称的多个参数。你可能只想用

做一次
comm.Parameters("@ProductID").Value = ItemSelect(ItemSelect.Count - 1)