Reputation: 109
I have this array in ASP
CONST CARTPID = 0
CONST CARTPRICE = 1
CONST CARTPQUANTITY = 2
dim localCart(3,20)
I add items to this array dynamically like this
localCart(CARTPID,i) = productId
localCart(CARTPRICE,i) = productPrice
localCart(CARTPQUANTITY,i) = 1
The problem is, after 4 items, I can still add the items but UBound always return 3. Which causing my conditions failing.
I want to increase size of this array at run time so that UBOUND can return latest value.
Please let me know how can i do that. Here is my complete code
'Define constants
CONST CARTPID = 0
CONST CARTPRICE = 1
CONST CARTPQUANTITY = 2
'Get the shopping cart.
if not isArray(session("cart")) then
dim localCart(3,20)
else
localCart = session("cart")
end if
'Get product information
productID = trim(request.QueryString("productid"))
productPrice = trim(request.QueryString("price"))
'Add item to the cart
if productID <> "" then
foundIt = false
for i = 0 to ubound(localCart)
if localCart(CARTPID,i) = productId then
localCart(CARTPQUANTITY,i) = localCart(CARTPQUANTITY,i)+1
foundIt = true
exit for
end if
next
if not foundIt then
for i = 0 to 20
if localCart(CARTPID,i) = "" then
***ReDim Preserve localCart(UBound(localCart, 1) + 1,20)***
localCart(CARTPID,i) = productId
localCart(CARTPRICE,i) = productPrice
localCart(CARTPQUANTITY,i) = 1
exit for
end if
next
end if
end if
Upvotes: 5
Views: 7266
Reputation: 3074
If your adding the items dynamically in a loop you'll want to use the Redim Preserve()
statement. You'll want to use the Preserve
part so you don't lose any of your existing data.
Otherwise if your using the array data and then redimming it for another set of data you can just the Redim()
statement
Here is a good reference on using Redim()
/ Redim Prevserve()
Statments: http://classicasp.aspfaq.com/general/can-i-create-an-array-s-size-dynamically.html
Upvotes: 5
Reputation: 8980
I think redimentioning the array with the current UBound+1 after each addition of new item will make UBound gives you the latest value finally.
// New item addition code will go here
ReDim localCart(UBound(localCart, 1) + 1,20)
So it will update your array with the new size every time you will add the new item.
Upvotes: 0
Reputation: 2586
The first dimension is only 3 in length, while the second dimension is 20. If you want the UBound of the second dimension, do this:
UBound(localCart, 2)
Which returns 20. You should be able to combine this with ReDim Preserve.
Upvotes: 1