In order to add objects from the Session use the following
method:
Listing 5
HttpSessionState.Session.Add(name,value);
This adds an object to the Session state, the name and the
value of the item to be added being passed to this method as parameters. Further,
the HttpSessionState class is present in the System.Web namespace in the
System.Web.dll file.
Alternatively, we can add objects to the Session.
Listing 6
HttpSessionState.Session[“UserName”] = “Joydip”;
This automatically creates a new item called “UserName” in
the Session State Collection (if none exists) and sets its value to “Joydip.”
The following method is used to retrieve a previously stored
object from the Session state.
Listing 7
string userName = HttpSessionState.Session["UserName"].ToString();
Note that the ToString() method is called because data is
stored in the Session state as objects. Therefore, the conversion or casting to
the appropriate type is necessary in the above example to retrieve the current
User’s name as a string.
The following method is used to remove an object from the
Session state.
HttpSessionState.Remove(objectName);
This method deletes the object specified as parameter from
the Session State Collection, provided the same exists. In this case, if the
session-state collection does not contain the element specified, the collection
remains unchanged, but no exception is thrown.
To clear the Session use either of the following:
or
The difference between the Session.Abandon() and the
Session.Clear() method is that if you call Session.Abandon(), Session_End will
be fired (for InProc mode) and in the next request, Session_Start will be
fired. Session.Clear( ) just clears the session data without killing it.