Code producing System.NullReferenceException error for Membership.GetUser(). This is VB.Net (ASP.Net 4)

Posted by Derrek on Stack Overflow See other posts from Stack Overflow or by Derrek
Published on 2010-12-26T23:47:00Z Indexed on 2010/12/26 23:53 UTC
Read the original article Hit count: 167

Filed under:

I have a Default.aspx page that is not static. I have added functionality with datalist and sqldatasources. When a user logins he/she will see items like saved workouts, saved equipment, total replys, etc... This is based on getting the currently logged in user UserID. Quite simply this works great when the user is logged in. However, I do not want to force a user to login to view the Default page because it does have functionality on it that does not require login. When a user is not logged in of course I receive the [System.NullReferenceException] error. I understand the error well but I do not know how to code to fix it. That is where I need help. I will admit I am more designer than developer. However, I do know the exception error I am receivving is caused by me not setting a value in my code when a user is not logged in. I do not know how to do that and have for a week made unsuccessful attempts at writing the code.

Both sets of code below compile for VB.Net/ASP.Net 4/Visual Studio 2010 without errors. However, I still get the System.NullReferenceException error if not logged in. I know it can be done but I do not know the right syntax. If you can help please insert you code in mine or write it out. JUST TELLING ME WHERE TO GO TO FIND AN ANSWER WON'T HELP. I HAVE DONE THAT FOR 7 STRAIGHT DAYS. I APPRECIATE OUR HELP.

Partial Class _Default Inherits System.Web.UI.Page

Protected Sub SqlDataSource4_Selecting(ByVal sender As Object, ByVal e As SqlDataSourceCommandEventArgs) Handles SqlDataSource4.Selecting
    Dim MemUser As MembershipUser

    MemUser = Membership.GetUser()

        If Not MemUser Is DBNull.Value Then
            UserID.Text = MemUser.ProviderUserKey.ToString()
            e.Command.Parameters("@UserId").Value = MemUser.ProviderUserKey.ToString()

    End If

End Sub

-------------------------------------ORIGINAL CODE-------------------------------

Partial Class _Default Inherits System.Web.UI.Page

Protected Sub SqlDataSource4_Selecting(ByVal sender As Object, ByVal e As SqlDataSourceCommandEventArgs) Handles SqlDataSource4.Selecting
    Dim MemUser As MembershipUser
    MemUser = Membership.GetUser()
    UserID.Text = MemUser.ProviderUserKey.ToString()
    e.Command.Parameters("@UserId").Value = MemUser.ProviderUserKey.ToString()
End Sub

© Stack Overflow or respective owner

Related posts about ASP.NET