2013-04-09 128 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; 
}