0

I want to add all of the items from a listbox inside of a list. This list is a string-list and a part of the private members from my object "Deur".

When i try to loop over the listbox listitems and add them inside this list, i get an error saying "System.NullReferenceException: 'Object reference not set to an instance of an object.'"

I've tried to Convert the "Listbox.Text" item to a string (which it alredy is), but that didn't help.

Here is the code where i try to add it to my list: LBSupplementen is the ListBox, b.SupplementenLijst is the List.

if (LBSupplementen.Items.Count > 0)
    foreach (ListItem i in LBSupplementen.Items)
        b.SupplementLijst.Add(Convert.ToString(i.Text));

and here is where i define my List in my object class "Deur":

private List<string> _SupplementLijst;
public Deur()
{
    _GaasID = GaasID;
    _Gaas = Gaas;
    _ProductID = ProductID;
    _Product = Product;
    _Hoogte = Hoogte;
    _Breedte = Breedte;
    _KleurID = KLeurID;
    _Kleur = Kleur;
    _SupplementLijst = SupplementLijst;
    _SupplementLijstID = SupplementLijstID;
    _Prijs = Prijs;
}


public List<string> SupplementLijst 
{ 
    get { return _SupplementLijst; }
    set { _SupplementLijst = value; } 
}
fhnaseer
  • 6,729
  • 16
  • 52
  • 101
Bapper
  • 11
  • 3
  • 3
    Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – S.L. Barth Mar 29 '19 at 12:55
  • either make sure you create an instance of your private member (then you can probably delete the setter of your SupplementLijst property) or create the list from your listitems and then use your property setter. – Geoffrey Mar 29 '19 at 12:58

1 Answers1

1

Have you instantiated the list in your "Deur" class? If not, make sure you instantiate your list in the constructor like this:

private List<string> MyList;
public Deur()
{ 
    MyList = new List<string>(); // Add this here
}

If you want your list to stay private, add a method to your "Deur" class that you can use to put items in your list from outside, like this:

public void AddToList(string item)
{
    MyList.Add(item);
}
Michael Jedd
  • 44
  • 1
  • 7