2013-04-22 17 views
1

我有一個類,它創建另一個類的列表。 它看起來像:訪問另一個類內的類的列表 - 空引用異常

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 
     } 
    } 

從我的Form1類我把這種方法(sortToClass()),它通過我的邏輯應填寫我的名單與該特定類。然後,我想寫list.count()到一個文本框:

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(); 
    } 

現在我的問題是,每當我試圖調試,停止我一個

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

然而,當我調試可以檢查當地人,其狀態如下:

sort -> listOfRec -> Count = 4. 

可能是什麼問題?

+0

是txt_out什麼是空? – 2013-04-22 18:45:26

+1

嘗試在調用'InitializeComponent'後運行代碼_after_;應該確保所有的控件(比如'txt_out')都被初始化了。 – 2013-04-22 18:45:57

+0

歡迎來到堆棧溢出!幾乎所有的'NullReferenceException'都是一樣的。請參閱「[什麼是.NET中的NullReferenceException?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)」的一些提示。 – 2013-04-22 18:46:04

回答

3

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

的InitializeComponent()後,因爲它是在方法中創建的。

+0

我剛剛意識到我確實需要在InitializeComponent之後調用方法。一直在考慮這樣的2小時:/我是一個延遲。感謝大家! :) – 2013-04-22 18:50:44

0

您應該將InitializeComponent();保留在該方法的頂部,因爲它會在窗體上創建所有控件。您可能正在獲取它,因爲您在創建並添加到表單之前試圖訪問控制txt_out