Exporting datagrid to CSV using Save Dialog in C#.NET

Below is the code for exporting the data of a data grid in C#.Net

Datagrid is as follows:




System.Windows.Forms.SaveFileDialog saveDlg = new System.Windows.Forms.SaveFileDialog();
                saveDlg.InitialDirectory = @"C:\";
                saveDlg.Filter = "CSV files (*.csv)|*.csv";
                saveDlg.FilterIndex = 0;
                saveDlg.RestoreDirectory = true;
                saveDlg.Title = "Export csv File To";
                if (saveDlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    string CsvFpath = saveDlg.FileName;
                    System.IO.StreamWriter csvFileWriter = new StreamWriter(CsvFpath, false);
                    string columnHeaderText = "";
                    int countColumn = comparisonGrid.Columns.Count - 1;
                    if (countColumn >= 0)
                    {
                        columnHeaderText = (comparisonGrid.Columns[0].Header).ToString();
                    }

                    // Writing column headers
                    for (int i = 1; i <= countColumn; i++)
                    {
                        columnHeaderText = columnHeaderText + ',' + (comparisonGrid.Columns[i].Header).ToString();
                    }
                    csvFileWriter.WriteLine(columnHeaderText);

                    // Writing values row by row
                    for (int i = 0; i <= comparisonGrid.Items.Count - 2; i++)
                    {
                        string dataFromGrid = "";
                        for (int j = 0; j <= comparisonGrid.Columns.Count - 1; j++)
                        {
                            if (j == 0)
                            {
                                dataFromGrid = ((DataRowView)comparisonGrid.Items[i]).Row.ItemArray[j].ToString();
                            }
                            else
                            {
                                dataFromGrid = dataFromGrid + ',' + ((DataRowView)comparisonGrid.Items[i]).Row.ItemArray[j].ToString();
                            }
                        }
                        csvFileWriter.WriteLine(dataFromGrid);
                    }
                    csvFileWriter.Flush();
                    csvFileWriter.Close();
                }

The content of output csv file looks like:

Comments