Friday, March 16, 2012

Passing an array as a Session varibale

Hi,

I have a problem passing an array as a session variable. here is my code.
page1.aspx

dim _title,_desc as String
dim i,_id,total As Integer
dim prs as project() ' project is a custom class
prs= D.getProjectsByHost(country) ' an array of projects.
total=prs.Length
For i = 0 To total- 1
_id =prs(i).prID
_title =prs(i).prTitle
_desc =prs(i).prDescription
''' here is what I need''
dim prArray() as string
prArray(_id)=_desc
session("prData")=prArray
next

I get an error for doing this: prArray(_id)=_desc
obect not set to an instance of object.........

in the next page"page2.aspx" I want to retreive the _desc for each project.

something like this:

dim dim prArray() as string
dim id = 45 ' for example
prArray=session("prData")
response.write(prArray(id))

thanks for any help.I could be wrong but dont you need to specify the size of the array?
Well, the reason you are getting an error is because you have not "initialized" an any elements for your array:

dim prArray() as string
prArray(_id)=_desc
You have no useable elements in the array (technically, you have nothing more than some allocated memory space; you have put nothing IN it yet). A better way to declare your array (if I follow your sample code correctly) would be:
dim prArray(total) as string
That should give you enough available elements in your array; that being said though, the above doesn't look like it is really the best way to pull off what you want.

A better way to arrange the data would probably be to make use of a HashTable object. HashTables allow you to create key/value pairs, and allow you ways of retrieving the values by searching with the key. Research on this object would reap great rewards, I'm sure...

Lastly, it's not necesarily a good idea to store objects in Session variables, if those objects are very large. This is because EACH USER will create and store THEIR OWN versions of the object, and if you have a high-traffic site, that could lead to serious performance issues. A (potentially) more performance-conscious method of storing this data in Session would be to store it as raw strings, and parse it as needed.

If you still feel you need to store the actual object in Session, the proper way to get it back out would be to use the CType() to cast it. Object in Session are of type Object; if you are retrieving a HashTable, you need to cast it BACK to a HashTable

'put the object in Session
Sesssion("myHashTable") = myHashTableObject
...
'get the object out of Session
Dim myNewHashTableObject = CType(Session("myHashTable"), HashTable)
HTH...

Chris
Thanks Chris, you idea of using hashtables is great. It solved my problem.

0 comments:

Post a Comment