string CsvFpath = saveFileDialog1.FileName; System.IO.StreamWriter csvFileWriter = new StreamWriter(CsvFpath, false);
if (saveFileDialog1.ShowDialog() == DialogResult.OK) { try {
string columnHeaderText = "";
int countColumn = dataGridView1.ColumnCount - 1;
if (countColumn >= 0) { columnHeaderText = dataGridView1.Columns[0].HeaderText; }
for (int i = 1; i <= countColumn; i++) { columnHeaderText = columnHeaderText + ',' + dataGridView1.Columns [i].HeaderText; }
csvFileWriter.WriteLine(columnHeaderText);
foreach (DataGridViewRow dataRowObject in dataGridView1.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();
MessageBox.Show("Export successful"); }