dictionary object in asp

They have: 426 posts

Joined: Feb 2005

Im trying to use the dictionary object in asp and it is working fine however i want to add a new object (key and item) to the dictionary dynamically....ie when a user clicks on a link it carries a value in the url that i want to add to the dictionary which will them used to search the database to display results in a table...it is going to be a shopping cart!

help appreciated. Below is what i have so far.

<html>
<body>
<%
Dim cart
Dim objDict
Dim PID
Dim x, y
PID = request.querystring("product_ID")

Set ORSp=server.createobject("ADODB.Connection")
ORSp.Open "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=" & Server.MapPath("20509703.mdb")
Set cart = Server.CreateObject("ADODB.Recordset")
<strong>Set objDict = Server.CreateObject("Scripting.Dictionary")</strong>

If PID <> "" Then

<strong> objDict.Add PID,1 </strong>

'looping through all the keys to retrieve their values for query

allKeys = objDict.Keys 'Get all the items into an array

For i = 0 To objDict.Count - 1

<strong> myKey = allkeys(i) </strong>

sqltext="Select * from products where product_ID ="&myKey
cart.Open sqltext, ORSp

while Not cart.EOF

  response.write(cart("PName")&"</br>")

cart.movenext
wend

cart.close

Next



'free up resources
set objDict=nothing

end If


%>
</body>
</html
'

Parts in bold are those that involve the dictionary. At the top you can see where i have just added one entry statically.

JeevesBond's picture

He has: 3,956 posts

Joined: Jun 2002

Hi ben, sorry this wasn't answered earlier. Is there a specific problem you're having with this?

The code above seems like it will work. It's not very efficient to do a SQL query for every iteration of that loop though, what would be better is to iterate through the dictionary building a string which will be the WHERE clause in your SQL statement.

Dictionaries are very optimised in ASP (and VB6 too) so are a good choice in this case. You might want to make your loop look a little more like:

For i = 0 To objDict.Count - 1
  myKey = allkeys(i)

  If i = 0 Then
    sqltext = "Select * from products where product_ID =" & myKey
  Else
    sqltext = sqltext & " or product_ID = " & myKey
  End If
Next

sqltext = sqltext & ";"

cart.Open sqltext, ORSp
cart.MoveFirst

while Not cart.EOF
  response.write(cart("PName")&"<br />")
  cart.movenext
wend

cart.close
'

Hope this makes sense! It's been a while since I did any ASP programming so please forgive any errors in that code. Smiling

a Padded Cell our articles site!

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.