Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy does this code throw a NullReferenceException when adding strings to listbox from a text file?
    primarykey
    data
    text
    <p>Here's the code:</p> <pre><code>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(); } </code></pre> <p>The evaluation array is irrelevant for now. I'm trying to display all the names in the names array into a listbox immediately upon launch. I also know that writing them into a text file and then reading them from it is a very roundabout way of doing things, but in this situation I have to. </p> <p>The problem is that it throws a NullReferenceException error right here:</p> <pre><code> //Writes name to listbox nameListBox.Items.Add(studentName); </code></pre> <p>For the life of me I can't figure out why. Is the original array not being written into the text file correctly? Or am I doing something wrong when trying to read back the strings?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload