title: Save datagridview to csv
body: <p>The problem is that I want what I did to my previous program that saved the data of a database in excel, now it does it in parameters separated by commas. I have searched for examples here in StackOverflow and I have had good results but I still can not get my code to do what I need.
  I leave my complete code.</p>
  
  <p>I leave the reference code but what I need help is in  private void SaveToCSV()</p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.ComponentModel;
  using System.Data;
  using System.Drawing;
  using System.IO;
  using System.Linq;
  using System.Text;
  using System.Threading.Tasks;
  using System.Windows.Forms;
  using IniFile;
  using Microsoft.Office.Interop.Excel;
  using SGP_Base.Classes;
  using Application = Microsoft.Office.Interop.Excel.Application;
  
  
  namespace MES_SERVER
  {
      public partial class FrmSerialAllResults : Form
      {
          public FrmSerialAllResults()
          {
              InitializeComponent();
              LoadDatas();
              CargarPermisos();
          }
          private void LoadDatas()
          {
              dataGridViewResults.Rows.Clear();
              serial_resultados serialResultados = new serial_resultados();
              serialResultados.SeleccionarDatos("");
              DatagridView(serialResultados, "No existen Resultados", serialResultados.Filas().Count - 50);
          }
          private void CargarPermisos()
          {
              Permisos permisos = new Permisos();
              Dictionary&lt;string, object&gt; parameters = new Dictionary&lt;string, object&gt;();
              parameters.Add("@objetos1", "Exportar a excel");
              permisos.SeleccionarDatos("objetos =@objetos1", parameters);
              buttonExportExcel.Enabled= Convert.ToBoolean(int.Parse(permisos.Filas()[0].Celda(Global.level).ToString()));
          }
          private void DatagridView(serial_resultados serialResultados, string mensaje, int total)
          {
              if (serialResultados.TieneFilas())
              {
                  //int inicio = serialResultados.Filas().Count - 50;
                  int inicio = total;
                  int k = 0;
                  foreach (Fila fila in serialResultados.Filas())
                  {
                      if (k &gt;= inicio)
                      {
                          dataGridViewResults.Rows.Add(fila.Celda("id"), fila.Celda("fecha"), fila.Celda("serial"),
                              fila.Celda("estacion"), " ", fila.Celda("status"),
                              fila.Celda("distancia"), fila.Celda("fuerza"), fila.Celda("vacio"), fila.Celda("presion"),
                              fila.Celda("tiempociclo"),
                              fila.Celda("total_ensamblados"), fila.Celda("ensamblado_a"));
                      }
                      k++;
                  }
                  for (int i = 0; i &lt; dataGridViewResults.Rows.Count; i++)
                  {
                      if (int.Parse(dataGridViewResults["Status", i].Value.ToString()) == 0)
                      {
                          dataGridViewResults["Status", i].Value = "NOK";
                          dataGridViewResults["Status", i].Style.BackColor = Color.OrangeRed;
                          dataGridViewResults["Status", i].Style.ForeColor = Color.White;
                      }
                      else
                      {
                          dataGridViewResults["Status", i].Value = "OK";
                          dataGridViewResults["Status", i].Style.BackColor = Color.LimeGreen;
                      }
                      string station = dataGridViewResults["Station", i].Value.ToString();
                      string newName =ObtenerNombre(station);
                      dataGridViewResults["nombre", i].Value = newName;
                  }
                  toolStripStatusLabelCounRows.Text = "Filas Totales: " + serialResultados.Filas().Count.ToString();
              }
              else
              {
                  MessageBox.Show(mensaje, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
              }
          }
          private string ObtenerNombre(string estation)
          {
              string numberstation = estation.Replace("E", "");
              Ini ini = new Ini(Global.PathFileIni);
              string name =ini.IniReadValue("Maquina" + numberstation, "Name");
              return name;
          }
          private string ObtenerEstacion(string name)
          {
              string pathFile = Global.PathFileIni;
              if (File.Exists(pathFile))
              {
                  Ini ini = new Ini(pathFile);
                  string valor = ini.IniReadValue("NumberTotalMachine", "Total");
                  if (valor != "")
                  {
                      int total = int.Parse(valor);
                      for (int i = 1; i &lt;= total; i++)
                      {
                          if (ini.IniReadValue("Maquina" + i, "Name") == name)
                          {
                              return "E" + i;
                          }
                      }
                  }
              }
              return "";
          }
          private void buttonExportExcel_Click(object sender, EventArgs e)
          {
              try
              {
                  //SaveExcel();
                   SaveToCSV();
              }
              catch{}
          }
  
           private void SaveToCSV()
           {
  
               string dataDay = DateTime.Today.ToString().Replace("/", "");
               dataDay = dataDay.Replace(":", "");
               dataDay = dataDay.Replace(" ", "");
  
               DataGridView dataGridViewResults = new DataGridView();
               SaveFileDialog sfd = new SaveFileDialog();
               string filename = "";
               string filter = "CSV file (*.csv)|*.csv| All Files (*.*)|*.*";
               sfd.FileName = "Registro_" + dataDay + ".csv";
               sfd.Filter = filter;
  
  
               if (sfd.ShowDialog() == DialogResult.OK)
               {
                   MessageBox.Show("Se estan exportando sus datos, se notificara cuando este listo");
                   if (File.Exists(filename))
                   {
                       try
                       {
                           File.Delete(filename);
                       }
                       catch (IOException ex)
                       {
                           MessageBox.Show("No fue posible escribir los datos en el disco" + ex.Message);
                       }
                   }
                   int columnCount = dataGridViewResults.ColumnCount;
                   string columnNames = "";
                   string[] output = new string[dataGridViewResults.RowCount + 1];
                   for (int i = 1; (i - 1) &lt; dataGridViewResults.RowCount; i++)
                   {
  
  
                       columnNames += dataGridViewResults.Columns[i].Name.ToString() + ",";
                   }
                   output[0] += columnNames;
                   for (int i = 1; (i - 1) &lt; dataGridViewResults.RowCount; i++)
                   {
                       for (int j = 0; j &lt; columnCount; j++)
                       {
  
                          output[i] += dataGridViewResults.Rows[i - 1].Cells[j].Value.ToString() + "/n";
                       }
                   }
                   System.IO.File.WriteAllLines(sfd.FileName, output, System.Text.Encoding.UTF8);
                   MessageBox.Show("El archivo esta listo para su uso");
               }
           } 
  
      /*    private void SaveExcel()
          {
              string dataDay = DateTime.Today.ToString().Replace("/", "");
              dataDay = dataDay.Replace(":", "");
              dataDay = dataDay.Replace(" ", "");
  
              SaveFileDialog saveFileDialog = new SaveFileDialog();
              saveFileDialog.Filter = "Excel Documents(*.xls)|*.xls";
              saveFileDialog.FileName = "Registro_" + dataDay + ".xls";
              if (saveFileDialog.ShowDialog() == DialogResult.OK)
              {
                  object Value = System.Reflection.Missing.Value;
                  Application excelApplication = new Application();
                  excelApplication.Visible = true;
                  Workbook workbook = excelApplication.Workbooks.Add(Value);
                  Worksheet worksheet = (Worksheet)workbook.Sheets["Sheet1"];
                  worksheet = (Worksheet)workbook.ActiveSheet;
                  worksheet.Cells[1, 1] = "Fecha";
                  worksheet.Cells[1, 2] = "Serial";
                  worksheet.Cells[1, 3] = "Estacion";
                  worksheet.Cells[1, 4] = "Nombre";
                  worksheet.Cells[1, 5] = "Estatus";
                  worksheet.Cells[1, 6] = "Distancia";
                  worksheet.Cells[1, 7] = "Fuerza";
                  worksheet.Cells[1, 8] = "Vacio";
                  worksheet.Cells[1, 9] = "Presion";
                  worksheet.Cells[1, 10] = "Tiempo de ciclo";
                  worksheet.Cells[1, 11] = "Total ensamblados";
                  worksheet.Cells[1, 12] = "Ensamblado a";
                  int FilasCount = dataGridViewResults.RowCount;
                  int k = 2;
                  for (int i = 0; i &lt; FilasCount; i++)
                  {
                      worksheet.Cells[k, 1] = dataGridViewResults["fecha", i].Value.ToString();
                      worksheet.Cells[k, 2] = dataGridViewResults["serial", i].Value.ToString();
                      worksheet.Cells[k, 3] = dataGridViewResults["Station", i].Value.ToString();
                      worksheet.Cells[k, 4] = dataGridViewResults["nombre", i].Value.ToString();
                      worksheet.Cells[k, 5] = dataGridViewResults["Status", i].Value.ToString();
                      worksheet.Cells[k, 6] = dataGridViewResults["distancia", i].Value.ToString();
                      worksheet.Cells[k, 7] = dataGridViewResults["fuerza", i].Value.ToString();
                      worksheet.Cells[k, 8] = dataGridViewResults["vacio", i].Value.ToString();
                      worksheet.Cells[k, 9] = dataGridViewResults["presion", i].Value.ToString();
                      worksheet.Cells[k, 10] = dataGridViewResults["tiempociclo", i].Value.ToString();
                      worksheet.Cells[k, 11] = dataGridViewResults["totalensambles", i].Value.ToString();
                      worksheet.Cells[k, 12] = dataGridViewResults["ensamblado_a", i].Value.ToString();
                      k++;
                  }
                  workbook.SaveAs(saveFileDialog.FileName, XlFileFormat.xlWorkbookNormal, Value, Value, Value, Value, XlSaveAsAccessMode.xlExclusive, Value, Value, Value, Value, Value);
                  workbook.Close(true, Value, Value);
                  excelApplication.Quit();
              }
          } */
          private void textBoxEstación_KeyPress(object sender, KeyPressEventArgs e)
          {
              if (e.KeyChar == 13)
              {
                  if (textBoxEstación.Text != "")
                      SearchEstacion();
                  else
                      LoadDatas();
                  textBoxEstación.Text = "";
              }
          }
          private void SearchEstacion()
          {
              string estacion = ObtenerEstacion(textBoxEstación.Text);
              if (estacion == "")
                  estacion = textBoxEstación.Text;
              dataGridViewResults.Rows.Clear();
              serial_resultados serialResultados = new serial_resultados();
              serialResultados.SeleccionarDatos("estacion='" + estacion + "'");
              DatagridView(serialResultados, "No existen datos para " + textBoxEstación.Text,0);
          }
          private void textBoxSerial_KeyPress(object sender, KeyPressEventArgs e)
          {
              if (e.KeyChar == 13)
              {
                  if (textBoxSerial.Text != "")
                      SearchSerial();
                  else
                      LoadDatas();
                  textBoxSerial.Text = "";
              }
          }
          private void SearchSerial()
          {
              dataGridViewResults.Rows.Clear();
              serial_resultados serialResultados = new serial_resultados();
              serialResultados.SeleccionarDatos("serial LIKE '%" + textBoxSerial.Text + "%'");
              DatagridView(serialResultados, "No existen datos para " + textBoxSerial.Text, 0);
          }
          private void textBoxEnsamble_KeyPress(object sender, KeyPressEventArgs e)
          {
              if (e.KeyChar == 13)
              {
                  if (textBoxEnsamble.Text != "")
                      SearchEnsamble();
                  else
                      LoadDatas();
                  textBoxEnsamble.Text = "";
              }
          }
          private void SearchEnsamble()
          {
              dataGridViewResults.Rows.Clear();
              serial_resultados serialResultados = new serial_resultados();
              serialResultados.SeleccionarDatos("ensamblado_a LIKE '%" + textBoxEnsamble.Text + "%'");
              DatagridView(serialResultados, "No existen datos para " + textBoxEnsamble.Text,0);
          }
          private void buttonReload_Click(object sender, EventArgs e)
          {
              LoadDatas();
          }
          private void dateTimePicker1_CloseUp(object sender, EventArgs e)
          {
              SearchDateTime();
          }
          private void SearchDateTime()
          {
              string Formato = "yyyy-MM-dd";
              string Date = dateTimePicker1.Value.ToString(Formato);
              dataGridViewResults.Rows.Clear();
              serial_resultados serialResultados = new serial_resultados();
              serialResultados.SeleccionarDatos("fecha LIKE '%" + Date + "%'");
              DatagridView(serialResultados, "No existen datos de la fecha " + Date,0);
          }
  
          private void dataGridViewResults_CellContentClick(object sender, DataGridViewCellEventArgs e)
          {
  
          }
      }
  }
  </code></pre>