在表单上显示类内容

时间:2013-04-09 16:31:59

标签: c# list class

我有一个工作列表由一个类填充(或者我假设)并且我试图在表单上的一组文本框中显示唯一的记录。

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

我收到错误(以**表示):

  

&#34;对象引用未设置为对象的实例。&#34;

我知道通过引用来处理类,如何尝试这种显示记录的方式?最终目标是能够使用currentPeopleShown变量自由地在多个记录之间滚动。

4 个答案:

答案 0 :(得分:0)

试试这个:

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

答案 1 :(得分:0)

您的peopleList超出范围。

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

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

数组未被使用,因此请使用peopleList:

txt_peopleName.Text = peopleList[currentPeopleshown].name;

您不需要numberOfPeople变量,只需使用peopleList.Count

即可

答案 2 :(得分:0)

你在哪里设置peopleArrayList?

在这些方面尝试一些事情:

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

    peopleArrayList.Add(data);

    numberOfPeople = 1;
    currentPeopleShown = 0;
}

答案 3 :(得分: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;
    }
}
相关问题