Object reference not set to an instance of an object.

Ernie Ahsir picture Ernie Ahsir · Mar 11, 2012 · Viewed 9.7k times · Source

My codes below don't have any errors during the compile time but when I open the page an error occur at the Guid currentUserId = (Guid)currentUser.ProviderUserKey; stating that Object reference not set to an instance of an object.

foreach(DataRowView ProfileInfo in UserProfileDataSource.Select(DataSourceSelectArguments.Empty))
            {
              //Some codes where I display data from database
            }



protected void UserProfileDataSource_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
    {
        MembershipUser currentUser = Membership.GetUser();

        Guid currentUserId = (Guid)currentUser.ProviderUserKey;

        e.Command.Parameters["USERID"].Value = currentUserId;
    }

and here is my SQLDataSource

<asp:SqlDataSource ID="UserProfileDataSource" runat="server" 
            ConnectionString="<%$ ConnectionStrings:ConnectionString %>" 
            onselecting="UserProfileDataSource_Selecting" 
            ProviderName="<%$ ConnectionStrings:ConnectionString.ProviderName %>"


            SelectCommand="SELECT &quot;TITLE&quot;, &quot;FAMILYNAME&quot;, &quot;GIVENNAME&quot;, &quot;MIDDLENAME&quot;, &quot;POSITION&quot;, &quot;INSTITUTIONNAME&quot;, &quot;USERID&quot;, &quot;REGISTEREDDATE&quot; FROM &quot;MEMBERINFO&quot; WHERE (&quot;USERID&quot; = ?)">
            <SelectParameters>
                <asp:Parameter Name="USERID" Type="Object" />
            </SelectParameters>
        </asp:SqlDataSource>

Ernie

Answer

Muad&#39;Dib picture Muad'Dib · Mar 11, 2012

you should check to make sure that currentUser is not null before trying to access it:

if ( currentUser != null )
{
/* do stuff here */
}
else
{
/* do something else, like show an error message perhaps */
}