1

I have a class which creates a list of another class. which looks like:

class SortItAll
{                                       
    Recipient rec;
    public List<Recipient> listofRec = new List<Recipient>();

    public void sortToClass()
    {
        while (isThereNextLine()) { //while there is a following line
            loadNextLine();         //load it

            rec = new Recipient(loadNextPiece(),  //break that line to pieces and send them as arguments to create an instance of "Recipient" class
                                loadNextPiece(),
                                loadNextPiece(),
                                loadNextPiece());
            listofRec.Add(rec);                   //add the created instance to my list
        }
    }

From my Form1 class I call this method (sortToClass()), which by my logic should fill my list with that specific class. Then I want to write the list.count() to a textbox:

    public Form1()
    {
        SortItAll sort = new SortItAll(); //create the instance of the class

        sort.sortToClass();               //within which i call the method to fill my list

        txt_out.Text = sort.listofRec.Count().ToString(); //writing out its count to a textbox

        InitializeComponent();
    } 

And now my problem is whenever I try to debug, it stops me with a

Nullreference exception pointing to -> "txt_out.Text = sort.listofRec.Count().ToString();" in Form1.

Yet, while debugging I can check the locals, where it states:

sort -> listOfRec -> Count = 4.

What might be the problem?

Peter O.
  • 28,965
  • 14
  • 72
  • 87
Senki Sem
  • 123
  • 9

2 Answers2

3

Put

 txt_out.Text = sort.listofRec.Count().ToString(); //writing out its count to a textbox

after InitializeComponent(), since it's created in that method.

  • I just realized indeed I've to call the method after InitializeComponent. been thinking about this like 2 hours :/ I'm a retard. thanks to you all! :) – Senki Sem Apr 22 '13 at 18:50
0

You should keep InitializeComponent(); at the top of the method as it creates all the controls on the form. You are probably getting it because you are trying to access control txt_out before it has been created and added to the form.

Justin
  • 3,289
  • 3
  • 14
  • 26