webdad3
webdad3

Reputation: 9090

adding object to collection

My roster object has the following property:

    [DataMember]
    public ObservableCollection<personDetail> personContact
    {
        get
        {
            return _personContact;
        }
        set
        {
            if (value != _personContact)
            {
                _personContact = value;
                NotifyPropertyChanged("personContact");
            }
        }
    }

personDetail contains:

    private string _name;
    private string _phone;
    private string _email;

and the get and set statements as well.

I'm trying to add the personDetail to my personContact property...

I've tried the following:

            roster myRoster;
            myRoster = roster.CreateNewRoster();

                personDetail myPerson;
                myPerson = personDetail.newPerson();

                myPerson.name = ph.tbNameValue.Text.ToString();
                myPerson.phone = ph.tbPhoneValue.Text.ToString();
                myPerson.email = "None Yet";

            myRoster.personContact.Add(myPerson);

as well as:

myRoster.personContact.Add(new personDetail() {name = myPerson.name, phone = myPerson.email});

Each time I'm getting a NullReferenceException when ever I try to add myPerson to personContact...

I'm probably doing something dumb... Can you identify what I'm doing incorrectly?

Thanks and Happy New Year!

Upvotes: 0

Views: 136

Answers (4)

Richard L
Richard L

Reputation: 1221

Does myRoster = roster.CreateNewRoster(); instanciate _personContact Otherwise it seems that it is null and then you call add on a null object.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1503899

That suggests nothing's setting personContact to an empty ObservableCollection<personDetail> to start with. I suggest that CreateNewRoster() should probably do that before returning it. Otherwise, do it yourself:

myRoster.personContact = new ObservableCollection<personDetail>();

As an aside, you should really try to follow the .NET naming conventions, where public types and properties are named with PascalCase, leading to type names of PersonDetail and Roster, as well as property names of Name, Phone, Email and PersonContact. I'd also rename PersonContact to something which sounds more understandable - possibly just Contacts?

Upvotes: 4

Oded
Oded

Reputation: 499382

You need to initialize Roster.personContact to something - an empty list for example:

myRoster.personContact = new ObservableCollection<personDetail>();

Upvotes: 3

Mark Byers
Mark Byers

Reputation: 839214

Perhaps you have never assigned anything to myRoster.personContact so it is still null.

I'd also suggest that you follow the Microsoft Naming Guidelines.

Upvotes: 1

Related Questions