Note that there are some explanatory texts on larger screens.

plurals
  1. POExporting datagridview to csv file
    primarykey
    data
    text
    <p>I'm working on a application which will export my DataGridView called scannerDataGridView to a csv file.</p> <p>Found some example code to do this, but can't get it working. Btw my datagrid isn't databound to a source.</p> <p>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.</p> <blockquote> <p>System.NullReferenceException: Object reference not set to an instance of an object. at Scanmonitor.Form1.button1_Click(Object sender, EventArgs e)</p> </blockquote> <p>Here is my Code, error is given on the following line:</p> <blockquote> <p>dataFromGrid = dataFromGrid + ',' + dataRowObject.Cells[i].Value.ToString();</p> </blockquote> <pre><code>//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 &gt;= 0) { columnHeaderText = scannerDataGridView.Columns[0].HeaderText; } for (int i = 1; i &lt;= 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 &lt;= countColumn; i++) { dataFromGrid = dataFromGrid + ',' + dataRowObject.Cells[i].Value.ToString(); csvFileWriter.WriteLine(dataFromGrid); } } } csvFileWriter.Flush(); csvFileWriter.Close(); } catch (Exception exceptionObject) { MessageBox.Show(exceptionObject.ToString()); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload