-1

I designed a form to import and export into database then I used this code to export table into csv button

but it always gives me that I have a problem inside the foreach "Object reference not set to an instance of an 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 += "\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);

}

Alex Gu
  • 9
  • 3

1 Answers1

1

Odds are, one of the cell's values is null. Performing a ToString() call on a null object will throw that exception. This might work instead:

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(",", ";") + ',';
}