Ndum'ndayi Mhlongo Ndum'ndayi Mhlongo - 1 year ago 85
Vb.net Question

How do i use Session Objects in ASP.NET (Using Visual Basic)

So i would like the user to login and have their username appear on the the top of the page when they're logged in. I check if they exist in the database first then i let them in, so when they click the login button it does something like this(button event)

If (IsPostBack) Then

command.Connection = connection

command.CommandText = "select count(*) from customer where Email='" & TextEmail.Text & "' AND Password='" & TextPassword.Text.Trim & "'"
counts = Convert.ToInt32(command.ExecuteScalar.ToString) ' execute this text as an SQL query

If (counts > 0) Then
Response.Redirect("Default.aspx", False)
Session("Username") = TextEmail.Text 'This is where i try to use the session storing the user's email (which i use as a username)
Label1.Visible = True
End If

End If

Above code works fine, has no problem. In C#.Net This would be Session["Username"]=TextEmail.Text right.

So now there is a form within my project to which you cannot gain access without logging in first. When this page loads, i want to check if the user is logged in or not, if not, I redirect them to the Login page, if they are i let them in, and update the label that will display "logged in user userEmail", The Page_load code is like this:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not (Session("Username") = vbNull) Then
LogInStatus.Text = "logged in user " & System.Web.HttpContext.Current.Session("Username").ToString
Response.Redirect("Login.aspx", False)
End If
Catch ex As Exception
End Try
End Sub

There will be a Logout, which when clicked i will set the Session to Null and then redirect them to the login page once again. so when they click logout this happens

Session("Username") = vbNull
Response.Redirect("Login.aspx", False)

When i run the code, i get this NullReference exception
image here
Obviously either i'm initializing the object wrong, or i'm just using it straight the wrong way. But all this works with C#. Please help.

Answer Source

The problem is: when "Username" key doesn't exists, the value you get from Session is the object Nothing, not vbNull. Then Nothing ToString raises an exception. Try this:

If Session("Username") IsNot Nothing Then
    LogInStatus.Text = "logged in user " & Session("Username").ToString
    Response.Redirect("Login.aspx", False)
End If

Rather than assigning vbNull you may do Session.Remove("Username") which sets the value to Nothing.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download