Pergunta

I'm working on a Login session through Visual Basic with asp.net. When the session timeout is complete and I click on another different page it gives me an error, "Object reference not set to an instance of an object." SessionState mode="InProc" Here is the code that I used for the session:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Session("Username") Is Nothing Then
        Label1.Text = "Welcome, " & Session("Username").ToString()
    End If
End Sub
Foi útil?

Solução

If Session("Username") IsNot Nothing Then
    Label1.Text = "Welcome, " & Session("Username").ToString()
Else
    Response.Redirect("~/Default.aspx")
End If

You need to check for if it's not null before you reference it. You were doing the opposite. You were checking to see if it's null, verifying it was, then referencing it. That's why you get a NullReferenceException. Basically all null reference exceptions are the same, you're trying to perform an operation on an object that is null.

Outras dicas

Use a built in function which is exactly what you are looking for :

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
 If Not IsNothing(Session("Username")) Then
    Label1.Text = "Welcome, " & Session("Username").ToString()
 End If
End Sub

That's all :=)

Cheers

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top