I'm having problem regarding session items. Before I use them, I want to check if they exists, but using this codes gives me error:
If (Session("SomeSessionItem") Is Nothing) Then
...
End If
This is the error:
Object reference not set to an instance of an object.
I think Session("SomeSessionItem")
tries to acquire the value of the session item. If the item doesn't exists then it throws exception. But how do I check if a session item exists before using them?
Home.aspx
. Home.aspx.vb
, I instantiate a WebUserControl SomeControl.ascx
. Note that in Home.aspx.vb
event handler Page_Load
I can use a condition to check session without getting an exception.SomeControl.ascx.vb
I'm trying to access the session, here's where the exception occurs.You can check whether a variable has been set in a user's session using the function isset(), as you would a normal variable. Because the $_SESSION superglobal is only initialised once session_start() has been called, you need to call session_start() before using isset() on a session variable.
Session["LoggedIn"] = "1"; Then check to see if it exists. If it doesn't then you know the session has been expired and recreated so you can boot them back. if (Session["LoggedIn"] == null) { Response.
You must try the following code: var IsNull= '@Session["CallType"]'!= null; Output: IsNull value will be true or false.
Does that work for you?
If (Session IsNot Nothing)
Dim item as Object = Session("SomeSessionItem")
If (item IsNot Nothing)
...
End If
End If
Also, you may need to check HttpContext.Current.Session
rather than simply Session
if you're seeing the the following error:
Session does not exist in this context
If you try to use sessions before the session object itself is created, you receive this behavior. Note that the Session object is not available at all times in the process of a request. You can check for Session itself to be Nothing.
It is guaranteed created after the Session_Start
event fired which you can check in global.asax.
In case your code runs inside the code-behind of your page, there are scenario's where the session state is not yet available. However, inside Page_Load it is available, check there.
Finally: when .EnableSessionstate="false"
is set for your page or application-wide, you cannot access the session object.
Maybe you mean instead of If (Session("SomeSessionItem") Is Nothing) Then
the following?
If (Session("SomeSessionItem") IsNot Nothing) Then
'... do someting, i.e.:'
Dim sessionItem As String = CType(Session("SomeSessionItem"), String)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With