-1

Online subject. Teacher gave us this but it doesn't run. Throws an error on line 48 where the fileWriter.WriteLine is System.NullReferenceException: 'Object reference not set to an instance of an object.'

Online tutorials look completely different

    public partial class frmMain : Form
    {
        private StreamWriter fileWriter;

        public class Record
        {
            public string Name { get; set; }
            public string ID { get; set; }
            public string Suburb { get; set; }
            public decimal Fee { get; set; }

        }

        string fileName = "student.txt";


        private void frmMain_Load(object sender, EventArgs e)
        {

            FileStream output = new FileStream(fileName,
                FileMode.OpenOrCreate, FileAccess.Write);

            fileWriter = new StreamWriter(output);
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            Record record = new Record();

            record.Name = txtName.Text;
            record.ID = txtID.Text;
            record.Suburb = txtSuburb.Text;
            record.Fee = Convert.ToDecimal(txtFee.Text);

            fileWriter.WriteLine(record.Name + "," + record.ID + "," +
                record.Suburb + "," + record.Fee); // Error here


            txtName.Text = "";
            txtID.Text = "";
            txtSuburb.Text = "";
            txtFee.Text = "";
        }

    }
  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Wai Ha Lee Apr 29 '19 at 18:29

1 Answers1

1

Your frmMain_Load isn't hooked up, click on the load event in the properties of the IDE, and select that method.

enter image description here

enter image description here

Badly hewn circle added for your enjoyment

TheGeneral
  • 79,002
  • 9
  • 103
  • 141