对象引用未设置为对象的实例IN c#export csv

时间:2015-12-24 18:28:47

标签: c# csv object reference instance

我设计了一个表单来导入和导出到数据库然后我用这个代码将表导出到csv按钮

但它总是让我在foreach内部遇到问题"对象引用没有设置为对象的实例"

        private void button5_Click(object sender, EventArgs e) 
    {
//Build the CSV file data as a Comma separated string.
string csv = string.Empty;

//Add the Header row for CSV file.
foreach (DataGridViewColumn column in dataGridView1.Columns)
{
    csv += column.HeaderText + ',';
}

//Add new line.
csv += "\r\n";

//Adding the Rows
foreach (DataGridViewRow row in dataGridView1.Rows)
{
    foreach (DataGridViewCell cell in row.Cells)
    {
        //Add the Data rows.
        csv += cell.Value.ToString().Replace(",", ";") + ',';
    }

    //Add new line.
    csv += "\r\n";
}

//Exporting to CSV.
string folderPath = "C:\\CSV\\";
File.WriteAllText(folderPath + "DataGridViewExport.csv", csv);

}

1 个答案:

答案 0 :(得分:1)

赔率是,单元格值之一是null。对null对象执行ToString()调用将抛出该异常。这可能会改为:

foreach (DataGridViewCell cell in row.Cells)
{
    object csvValue = (cell == null || cell.Value == null) ? string.Empty : cell.Value;
    //Add the Data rows.
    csv += csvValue.ToString().Replace(",", ";") + ',';
}