RD Design

RD Design

  • NA
  • 25
  • 25.8k

How to save datagridview as csv file?

May 30 2017 9:26 AM
Hi,

I have a datagridview windows form with some data.I want to export that as a csv file.Here is my code and it gives an error while export.My guess is becuase of some empty values in cells.How can I fix this issue?
 
 

  1. public void writeCSV(DataGridView gridIn, string outputFile)  
  2.         {  
  3.             string filename = "";  
  4.             SaveFileDialog sfd = new SaveFileDialog();  
  5.             sfd.Filter = "CSV (*.csv)|*.csv";  
  6.             sfd.FileName = "Output.csv";  
  7.             if (sfd.ShowDialog() == DialogResult.OK)  
  8.             {  
  9.                 MessageBox.Show("Data will be exported and you will be notified when it is ready.");  
  10.                 if (File.Exists(filename))  
  11.                 {  
  12.                     try  
  13.                     {  
  14.                         File.Delete(filename);  
  15.                     }  
  16.                     catch (IOException ex)  
  17.                     {  
  18.                         MessageBox.Show("It wasn't possible to write the data to the disk." + ex.Message);  
  19.                     }  
  20.                 }  
  21.                 int columnCount = dataGridView1.ColumnCount;  
  22.                 string columnNames = "";  
  23.                 string[] output = new string[dataGridView1.RowCount + 1];  
  24.                 for (int i = 0; i < columnCount; i++)  
  25.                 {  
  26.                     columnNames += dataGridView1.Columns[i].Name.ToString() + ",";  
  27.                 }  
  28.                 output[0] += columnNames;  
  29.                 for (int i = 1; (i - 1) < dataGridView1.RowCount; i++)  
  30.                 {  
  31.                     for (int j = 0; j < columnCount; j++)  
  32.                     {  
  33.                         output[i] += dataGridView1.Rows[i - 1].Cells[j].Value.ToString() + ",";  
  34.                     }  
  35.                 }  
  36.                 System.IO.File.WriteAllLines(sfd.FileName, output, System.Text.Encoding.UTF8);  
  37.                 MessageBox.Show("Your file was generated and its ready for use.");  
  38.             }  
  39.         } 

Answers (6)