Senki Sem
Senki Sem

Reputation: 131

Accessing a list of class from within another class - null reference exception

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?

Upvotes: 1

Views: 374

Answers (2)

Justin
Justin

Reputation: 3397

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.

Upvotes: 0

Jim W
Jim W

Reputation: 5016

Put

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

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

Upvotes: 3

Related Questions