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



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

但它总是让我在foreach"Object reference not set to a instance of a Object"中遇到问题

        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 += "rn";
//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 += "rn";
}
//Exporting to CSV.
string folderPath = "C:\CSV\";
File.WriteAllText(folderPath + "DataGridViewExport.csv", csv);

}

奇数是,单元格的值之一是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(",", ";") + ',';
}

相关内容

  • 没有找到相关文章

最新更新