0

I am not able to write to a file using the CsvHelper and receive the following error at line: foreach (CSV3 sa in cSV3BindingSource.DataSource as List<CSV3>):

System.NullReferenceException: 'Object reference not set to an instance of an object.'
(... as System.Collections.Generic.List) returned null.

private void Save_Click(object sender, EventArgs e)
{
    using (SaveFileDialog sfd = new SaveFileDialog() { Filter = "CSV|*.csv", ValidateNames = true })
    {

        if (sfd.ShowDialog() == DialogResult.OK)
        {
            using (var sw = new StreamWriter(sfd.FileName))
            {
                var writer = new CsvWriter(sw);
                writer.WriteHeader(typeof(CSV3));

                foreach (CSV3 sa in cSV3BindingSource.DataSource as List<CSV3>) 
                {             
                    writer.WriteRecord(sa);
                }
            }
            MessageBox.Show("File has been saved", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);

        }
    }
}

I'm not sure what is causing that null reference exception.

rene
  • 37,946
  • 78
  • 99
  • 132
Sama
  • 11
  • 1

0 Answers0