Hi i have the following code to export a datagrid view and save it. Now i want that after the user saves the export file it opens. What to do?

private void ExportDGV(DataGridView dgv)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "Comma Separated Values (*.csv)|*.csv";

            if (sfd.ShowDialog() == DialogResult.OK)
            {
                TextWriter tw = new StreamWriter(sfd.FileName + ".csv");

                for (int i = 0; i < dgv.Rows.Count; i++)
                {
                    for (int j = 0; j < dgv.Columns.Count; j++)
                        tw.Write(dgv.Rows[i].Cells[j].Value.ToString().Replace(",", "','") + ",");
                    tw.WriteLine();
                }
                tw.Close();
            }
            
        }

CSV File seperates a row data by comma (,).So you have to use a StreamReader, and split the row (line) by comma. these seperated data are for columns.

The code bellow as you can see is create for not knowing the actual *.csv file. Code creates a new dataTable, creates appropriate number of columns and then fill dataTable up, based on number of rows (and based on number of columns for each row).

Here is the code it might code right:

DataTable table = new DataTable("myTable");
            bool bCreateColumns = true;
            using (StreamReader sr = new StreamReader(@"C:\1\testCSVfile.csv"))
            {
                int rows = 0;
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    string[] columns = line.Split(new char[] { ';' }, StringSplitOptions.None);
                    if (bCreateColumns)
                    {
                        DataColumn[] dtColumns = new DataColumn[columns.Length];
                        int colCounter = 1;
                        foreach (DataColumn col in dtColumns)
                            table.Columns.Add("column" + colCounter++, typeof(string));
                        bCreateColumns = false;
                    }

                    for (int i = 0; i < columns.Length; i++)
                    {
                        table.Rows.Add();
                        table.Rows[rows][i] = columns[i];
                    }
                    rows++;
                }
            }
            dataGridView1.DataSource = new BindingSource(table, null);

Actually the seperator is semicolon ";" not a comma. My mistake before in the upper post! I applogize for that.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.