<gr******@comcast.net> wrote in message
news:11**********************@f14g2000cwb.googlegr oups.com...
This is very helpful. I have one question though. Where do i declare
the session variables? Since I ran into this problem, I have been
reading many groups and researching the problem. Do I declare the
variables in global.asax or on each webform? Thanks in advance.
You don't have to declare them at all. They're not "variables", really.
"Session" (aka Page.Session, or Page.Context.Session) is an instance of the
HttpSessionState class. You can treat it as a collection of name-value
pairs. You can set a value with syntax like
Session("FirstName") = TheFirstNameValue
and then you can retrieve it with
Dim o As Object = Session("FirstName")
Note that Session(string) returns an Object, so you'll have to cast it to
the correct type:
Dim s As String = DirectCast(Session("FirstName"), String)
Note the use of DirectCast, which is correct since you know that it's a
string (you put it there, after all). Do not use CType or ToString in these
cases, as though you didn't know what type of value you put there.
Note also that this is subject to spelling errors - Session("FirstNam") will
return Nothing. I usually solve this problem by wrapping session state in a
class and using properties of the class to access it:
Public Class UserState
....
Public Shared Property FirstName As String
Get
Return DirectCast(HttpContext.Current.Session("FirstName" ),
String)
End Get
Set(ByVal Value As String)
HttpContext.Current.Session("FirstName") = Value
End Set
End Property
...
End Class
This way, there are only two places for a typo to happen. I would access
this from a page as UserState.FirstName. This can be accessed from multiple
pages.
BTW, Note the use of HttpContext.Current.Session. Since class UserState
isn't a Page, it doesn't have a "Session" member, so the Shared HttpContext
member "Current" is used to access the current request context.
John Saunders