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?
- public void writeCSV(DataGridView gridIn, string outputFile)
- {
- string filename = "";
- SaveFileDialog sfd = new SaveFileDialog();
- sfd.Filter = "CSV (*.csv)|*.csv";
- sfd.FileName = "Output.csv";
- if (sfd.ShowDialog() == DialogResult.OK)
- {
- MessageBox.Show("Data will be exported and you will be notified when it is ready.");
- if (File.Exists(filename))
- {
- try
- {
- File.Delete(filename);
- }
- catch (IOException ex)
- {
- MessageBox.Show("It wasn't possible to write the data to the disk." + ex.Message);
- }
- }
- int columnCount = dataGridView1.ColumnCount;
- string columnNames = "";
- string[] output = new string[dataGridView1.RowCount + 1];
- for (int i = 0; i < columnCount; i++)
- {
- columnNames += dataGridView1.Columns[i].Name.ToString() + ",";
- }
- output[0] += columnNames;
- for (int i = 1; (i - 1) < dataGridView1.RowCount; i++)
- {
- for (int j = 0; j < columnCount; j++)
- {
- output[i] += dataGridView1.Rows[i - 1].Cells[j].Value.ToString() + ",";
- }
- }
- System.IO.File.WriteAllLines(sfd.FileName, output, System.Text.Encoding.UTF8);
- MessageBox.Show("Your file was generated and its ready for use.");
- }
- }

Rijwan AnsariRank #82 · 24.2K reputationPosted Feb 12, 2021, 6:29 AM EST
Vivek KumarRank #272 · 9.3K reputationPosted May 30, 2017, 12:13 PM EDT
Tapan PatelRank #614 · 3.9K reputationPosted May 31, 2017, 10:35 AM EDT
Camilo Vega5 reputationPosted Feb 11, 2021, 10:59 PM EST
Jignesh KumarRank #91 · 22.9K reputationPosted Feb 11, 2021, 11:40 PM EST
Satya KarkiRank #78 · 24.6K reputationPosted Feb 13, 2021, 5:20 AM EST