PandaNL PandaNL - 17 days ago 4
C# Question

Exporting datagridview to csv file

I'm working on a application which will export my DataGridView called scannerDataGridView to a csv file.

Found some example code to do this, but can't get it working. Btw my datagrid isn't databound to a source.

When i try to use the Streamwriter to only write the column headers everything goes well, but when i try to export the whole datagrid including data i get an exeption trhown.


System.NullReferenceException: Object reference not set to an instance
of an object. at Scanmonitor.Form1.button1_Click(Object sender,
EventArgs e)


Here is my Code, error is given on the following line:


dataFromGrid = dataFromGrid + ',' + dataRowObject.Cells[i].Value.ToString();


//csvFileWriter = StreamWriter
//scannerDataGridView = DataGridView

private void button1_Click(object sender, EventArgs e)
{
string CsvFpath = @"C:\scanner\CSV-EXPORT.csv";
try
{
System.IO.StreamWriter csvFileWriter = new StreamWriter(CsvFpath, false);

string columnHeaderText = "";

int countColumn = scannerDataGridView.ColumnCount - 1;

if (countColumn >= 0)
{
columnHeaderText = scannerDataGridView.Columns[0].HeaderText;
}

for (int i = 1; i <= countColumn; i++)
{
columnHeaderText = columnHeaderText + ',' + scannerDataGridView.Columns[i].HeaderText;
}


csvFileWriter.WriteLine(columnHeaderText);

foreach (DataGridViewRow dataRowObject in scannerDataGridView.Rows)
{
if (!dataRowObject.IsNewRow)
{
string dataFromGrid = "";

dataFromGrid = dataRowObject.Cells[0].Value.ToString();

for (int i = 1; i <= countColumn; i++)
{
dataFromGrid = dataFromGrid + ',' + dataRowObject.Cells[i].Value.ToString();

csvFileWriter.WriteLine(dataFromGrid);
}
}
}


csvFileWriter.Flush();
csvFileWriter.Close();
}
catch (Exception exceptionObject)
{
MessageBox.Show(exceptionObject.ToString());
}

Answer

Found the problem, the coding was fine but i had an empty cell that gave the problem.