classic asp dictionary not working

Found an interesting feature of the classic dictionary object. Consider this code block:

dim conn
dim rs
dim myDictionary

set conn = server.CreateObject("ADODB.connection") connPublic
'connPublic is just a normal connection string

set rs = server.CreateObject("ADODB.recordset")

set myDictionary = Server.CreateObject("Scripting.Dictionary") "SELECT [id],[pagename] FROM [maincontent]",conn,3

do while not rs.eof
    myDictionary.add cstr(rs("id")), rs("pagename")

set rs = nothing
set conn = nothing
dim i
for each i in myDictionary
    response.write(myDictionary.item(i) & "<br>")

set myDictionary = nothing

This seemingly plausible block of code returns the highly descriptive error '80020009'.

It appears that this error is due to the dictionary add method not really doing what it says on the tin, i.e. not adding. Fortunately there is a work around for this problem - change

myDictionary.add cstr(rs("id")), rs("pagename")


myDictionary(cstr(rs("id"))) = rs("pagename")

Doing this forces the dictionary object to create a new item with the name you have specified, much like what you would expect the 'add' method to do...


Posted on Friday, August 24, 2012 2:33:00 PM GMT by Matheus
You can also use
myDictionary.add rs("id").Value, rs("pagename").Value
Posted on Monday, November 26, 2012 9:42:00 PM GMT by Gary R
I just spent about 30 minutes troubleshooting someone else's code because they were using .add

This fixed it right up. Thank you!!!
Posted on Saturday, December 20, 2014 12:08:00 AM GMT by Grant
I think this may be caused by a problem with the recordset cursor type. I've resolved the error by something like:

strID = rs("id")
strPageName = rs("pagename")
myDictionary.add strId, strPageName
Posted on Wednesday, July 12, 2017 8:04:00 PM GMT by Michael Bernholtz
Same as Gary,
Trying to use Add and it worked after this.

Post a comment