2013-04-09 96 views
0

我有一個工作列表由一個類填充(或者我假設),並試圖在窗體上的一組文本框中顯示唯一的記錄。在窗體上顯示類內容

public partial class frm_people : Form 
{ 

    public frm_people() 
    { 
     // Loads the Form 
     InitializeComponent(); 

     LoadData(); 

     ShowData(); 

    } 

    // Global Variables 

    private People peopleClass; 
    private ArrayList peopleArrayList; 

    private int numberOfPeople; 
    private int currentPeopleShown; 

    private void ShowData() 
    { 
     // Add to Text Box based on current Record 
     txt_peopleName.Text = ((People)peopleArrayList[currentPeopleshown]).name;** 
    } 

    private void LoadData() 
    { 

     List<People> peopleList = new List<People>(); 

     People data = new People("James Bond", false, "Cardiff"); 

     peopleList.Add(data); 

     numberOfPeople = 1; 
     currentPeopleShown = 0; 
    } 
} 

我得到一個錯誤(由**注):「未設置爲一個對象的實例對象引用」

我知道類是通過引用工作,如何嘗試這種顯示記錄的方式?最終目標是通過使用currentPeopleShown變量,可以自由滾動多個記錄。

+1

我沒有看到peopleArrayList被設定。如果它從未設置,那麼值爲空,這就是爲什麼你會得到這個錯誤。 – atbebtg 2013-04-09 16:38:26

回答

0

或者你可以消除的ArrayList一起,只是這樣做

public partial class frm_people : Form 
{ 
    List<People> peopleList; 
    public frm_people() 
    { 
     // Loads the Form 
     InitializeComponent(); 

     peopleList = new List<People>(); 
     LoadData(); 

     ShowData(); 

    } 

    // Global Variables 

    private People peopleClass; 

    private int numberOfPeople; 
    private int currentPeopleShown; 

    private void ShowData() 
    { 
     // Add to Text Box based on current Record 
     txt_peopleName.Text = (peopleList[0]).name;** 
    } 

    private void LoadData() 
    { 

     People data = new People("James Bond", false, "Cardiff"); 

     peopleList.Add(data); 

     numberOfPeople = 1; 
     currentPeopleShown = 0; 
    } 
} 
+0

我試過這個,但錯誤狀態「peopleList在當前上下文中不存在」當我將LoadData方法移動到ShowData之一時,整個事情就起作用了。我想我可能對課堂本身有問題,我會研究它。謝謝! – user2261755 2013-04-09 20:04:48

0

試試這個:

private void ShowData() 
    { 
     // Add to Text Box based on current Record 
     if(peopleArrayList[currentPeopleshown]!=null) 
     txt_peopleName.Text = ((People)peopleArrayList[currentPeopleshown]).name; 
    } 
+0

相同的錯誤會在if行的結尾出現。 – user2261755 2013-04-09 16:37:13

0

你peopleList超出範圍。

List<People> peopleList = new List<People>(); 

private void LoadData() 
{ 
    //... 
} 

數組沒有被使用,所以使用peopleList:

txt_peopleName.Text = peopleList[currentPeopleshown].name; 

你不會需要numberOfPeople變量,你可以使用peopleList.Count

0

你在哪裏設置peopleArrayList ?

試試這些線路上:

private void LoadData() 
{ 
    peopleArrayList = new ArrayList(); 
    People data = new People("James Bond", false, "Cardiff"); 

    peopleArrayList.Add(data); 

    numberOfPeople = 1; 
    currentPeopleShown = 0; 
}