Question

I have a custom profile defined in my webconfig. I have this property defined

<add name="sex" type="bool" serializeAs="String" defaultValue="[null]"/>

as there are null values in the database. I get a null reference exception in this code:

    ProfileCommon p = GetProfile();
            txtFirstName.Text = p.first_name;
            txtLastName.Text = p.last_name;
            txtInitial.Text = p.initial;
            txtEmail.Text = p.email;

//this causes an null reference exception bool? blnTest = p.sex;

Is this the correct way to set a default null value in webconfig?

Was it helpful?

Solution

The problem here is that the default type of a profile property is bool which is not a nullable type. It will always default to false.

You could always create a custom class to encapsulate Sex / Gender and use this instead of bool. That way when there is no value set the class will then attempt to instantiate and revert to null as required.

Changes to web config:

 <profile defaultProvider="MyProfileProvider" inherits="FTS.Membership.Profile.MyProfileProvider,FTS.Membership">
      <providers>
        <clear/>
        <add name="MyProfileProvider" connectionStringName="LocalSqlServer" applicationName="/" type="FTS.Membership.Profile.MyProfileProvider,FTS.Membership"/>
      </providers>
      <properties>
        <add name="first_name" type="string" serializeAs="String" defaultValue=""/>
        <add name="last_name" type="string" serializeAs="String" defaultValue=""/>
        <add name="initial" type="string" serializeAs="String" defaultValue=""/>
        <add name="email" type="string" serializeAs="String"/>
        <add name="active" type="bool" serializeAs="String" defaultValue="false"/>
        <add name="creation_date" type="datetime" serializeAs="String"/>
        <add name="update_date" type="datetime" serializeAs="String"/>
        <add name="last_activity_date" type="datetime" serializeAs="String"/>
        <!--<add name="sex" type="bool" serializeAs="String" defaultValue="false"/>-->

      </properties>
    </profile>

and the class:

using System;
using System.Web.Profile;
using System.Collections.Generic;

namespace FTS.Membership.Profile
{
    public class MyProfileProvider : ProfileBase
    {
        public bool? sex
        {
            get {
                if (base["sex"] == null)
                {
                    return null;
                }
                return (bool)base["sex"];
            }
            set { base["sex"] = value; }
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top