Friday, March 16, 2012

Looping through values of Session

What would the syntax be to loop through all the values of a current session along with the name of each variable?

for example:


sub page_load(sender as object, e as Eventargs)
if not page.ispostback then
Session("item1") = "10.00"
Session("item2") = "20.00"
Session("item3") = "30.00"
end if
numberOfItems.text=Session.count
Dim item as DictionaryEntry

for each item in Session.contents
' CODE GOES HERE TO DISPLAY NAME AND VALUE PAIRS
next

I can get the value of a session variable if i know it's name but that doesn't help me for what I am doing.

TIA

DJYou may do somethong like this:


Dim I As Integer = 0
Dim L As Integer = Session.Contents.Count
Dim Value(L) As String
For I = I To L - 1
Value(I) = Session.Contents.Item(I).ToString()
Next

You can try something as follows
 foreach (string s1 in Session.Keys) {
if (Session[s1] != null)
Response.Write(s1 + " " + Session[s1].ToString() + "<br/");
}

Hope that helps
Kashif
JimmyM

Thanks for that. One last question - this returns the values of all the items in the session - but how would I get access to the name of the variable for each value?

I tried Session.Contents.Key(I).ToString() but "key" isn't a member of the HTTPSessionState object - how would i access the name of the variable?

Thanks for all your help so far.

DJ
In the sample I posted above - string "s1" represents the name of the variable in session.

HTH
Kashif
Like Kashif said, you need to use "Keys" not "Key", like this:


Dim I As Integer = 0
Dim L As Integer = Session.Contents.Count
Dim Value(L) As String
Dim keyName(L) As String

For I = I To L - 1

Value(I) = Session.Contents.Item(I).ToString()
keyName(I) = Session.Contents.Keys(I).ToString()

Next


Ahh..

JimmyM and Kashif, you guys rock. Thank you so much!

Dj
Well,

The code seems nice and easy, but I got this error:
CS0118: 'System.Web.UI.Page.Session' denotes a 'property' where a 'class' was expected

And the hightlight is for this line:
foreach (string s1 in Session.Keys) {

0 comments:

Post a Comment