无法使用csvHelper C#

时间:2017-11-19 13:38:01

标签: c# csvhelper

我无法使用CsvHelper写入文件并在第foreach (CSV3 sa in cSV3BindingSource.DataSource as List<CSV3>)行收到以下错误:

  

System.NullReferenceException:'对象引用未设置为对象的实例。'    (...作为System.Collections.Generic.List)返回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);

        }
    }
}

我不确定导致该空引用异常的原因。

0 个答案:

没有答案