Monday, March 26, 2012

object reference error message

hi folks, i've been getting this error message but i can't seem to figure out whats wrong

"object reference not set to an instance of an object"

here's the line it is refering to:

browserIDValue.Text = Membership.GetUser().ProviderUserKey.ToString()

any help would be great, thanks

It means, that the portion of your code Membership.GetUser().ProviderUserKey is comming up as nothing, so you cant do a .tostring on it

This function only works for the currently logged in user - and I think it gets a little funny if you are using windows authentication. Make sure you are logged in before you call the GetUser method, or specify which user you want to get in the GetUser(parms)


Check the following stuff:
if (Membership.GetUser() ==null && Membership.GetUser().ProviderUserKey ==null)throw new Exception("User is not logged in");Membership.GetUser().ProviderUserKey.ToString();

I guess that one of these two is available as the User is not authenticated.

Hope that helps,
Matthias :)


cheers guys, got that sorted, I'm having a similar promblem on another page where I'm inserting two rows into a table, I'm getting the same error as above when I attempt the second insert but the first insert works fine, its a bit confusing since they should be getting the same information, just the parameters swapped round

Protected Sub addFriend_ItemInserting(ByVal senderAs Object,ByVal eAs System.Web.UI.WebControls.DetailsViewInsertEventArgs)Handles addFriend.ItemInserting e.Values("userID_1") = Membership.GetUser().ProviderUserKey e.Values("userID_2") = Request.QueryString("userID")End SubProtected Sub getFriends_Inserted(ByVal senderAs Object,ByVal eAs System.Web.UI.WebControls.SqlDataSourceStatusEventArgs)Handles getFriends.InsertedDim DataSourceAs SqlDataSource =CType(FindControl("addFriend_2"), SqlDataSource)Dim userID_1 = Request.QueryString("userID")Dim userID_2 = Membership.GetUser().ProviderUserKey DataSource.InsertParameters.Add("userID_1", userID_1) DataSource.InsertParameters.Add("userID_2", userID_2) DataSource.Insert()End Sub

Always check whether a object exists (is instantiated) as explained before!

If you are sure you can use the object, access it. Otherwise you'll end up with quite a lot of those errors in bigger projects. NEVER assume a object is accessible.

Cheers,
Matthias :)

0 comments:

Post a Comment