为什么在从文本文件向列表框添加字符串时,此代码会抛出NullReferenceException?

时间:2013-11-21 18:13:33

标签: c# visual-studio-2010 text listbox

以下是代码:

public partial class Form1 : Form
{
    //Initialize Array to hold student names
    new string[] names = { "David Palladini", "Michael Reyes", "Bram Lesser", "Hans Herrmann", "Nathan Texeira" };

    //Initialize Array to hold student evaluations
    new double[,] evaluation = { {1.0, 0.8, 0.9 ,1.0,0.6},
                                 {0.2, 0.9, 0.5, 0.6, 0.7},
                                 {0.5, 1.0, 1.0, 1.5, 0.9},
                                 {0.9, 0.9, 0.9, 1.0, 1.0},
                                 {1.0, 0.9, 1.0, 0.8, 0.9} };


    public Form1()
    {
        StreamWriter outputFile;
        outputFile = File.CreateText("names.txt");

        foreach (string name in names)
        {
            outputFile.WriteLine(name);
        }

        outputFile.Close();

        string studentName;
        StreamReader inputFile;
        inputFile = File.OpenText("names.txt");

        while (!inputFile.EndOfStream)
        {
            //Reads name from text file
            studentName = inputFile.ReadLine();

            //Writes name to listbox
            nameListBox.Items.Add(studentName);
        }

        inputFile.Close();

        InitializeComponent();
    }

评估数组目前无关紧要。我试图在启动时立即将names数组中的所有名称显示到列表框中。我也知道将它们写入文本文件然后从中读取它是一种非常迂回的做事方式,但在这种情况下我必须这样做。

问题是它在这里抛出NullReferenceException错误:

        //Writes name to listbox
        nameListBox.Items.Add(studentName);

对于我的生活,我无法弄清楚为什么。原始数组是否未正确写入文本文件?或者在尝试回读字符串时我做错了什么?

2 个答案:

答案 0 :(得分:3)

在调用nameListBox之前我不相信InitializeComponent();会尝试将该行移动到Form1构造函数的顶部。

答案 1 :(得分:1)

尝试将初始化移至顶部:

public Form1()
{
    InitializeComponent();
    StreamWriter outputFile;
    outputFile = File.CreateText("names.txt");

    foreach (string name in names)
    {
        outputFile.WriteLine(name);
    }

    outputFile.Close();

    string studentName;
    StreamReader inputFile;
    inputFile = File.OpenText("names.txt");

    while (!inputFile.EndOfStream)
    {
        //Reads name from text file
        studentName = inputFile.ReadLine();

        //Writes name to listbox
        nameListBox.Items.Add(studentName);
    }

    inputFile.Close();


}