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);
}