title: How to export my DataGridView to a csv file?
body: <p>I'm trying to export my <code>DataGridView</code> to <code>csv</code> file with this code:</p>
  
  <pre><code>private void saveToCsv(DataGridView dGV, string filename)
  {
      if (dGV.RowCount &gt; 0)
      {
          DataTable dt = new DataTable();
          dt = dGV.DataSource as DataTable;
          int d = dt.Columns.Count;
          int c = dt.Rows.Count;
          foreach (var column in dt.Columns.Cast&lt;DataColumn&gt;().ToArray())
          {
              if (dt.AsEnumerable().All(dr =&gt; dr.IsNull(column)))
                  d--;
          }
          string stOutput = "";
          DataGridViewRow ds = new DataGridViewRow();
          StreamWriter swOut = new StreamWriter(filename);
  
          //write header rows to csv
          for (int i = 0; i &lt;= d - 1; i++)
          {
              if (i &gt; 0)
              {
                  swOut.Write(",");
              }
              swOut.Write(dGV.Columns[i].HeaderText);
          }
  
          swOut.WriteLine();
  
          //write DataGridView rows to csv
          for (int j = 0; j &lt;= c - 1; j++)
          {
              if (dt.Rows[j].IsNull)
              if (j &gt; 0)
              {
                  swOut.WriteLine();
              }
  
              ds = dGV.Rows[j];
  
              for (int i = 0; i &lt;= d - 1; i++)
              {
                  if (i &gt; 0)
                  {
                      swOut.Write(",");
                  }
  
                  stOutput = ds.Cells[i].Value.ToString();
                  //replace comma's with spaces
                  stOutput = stOutput.Replace(',', ' ');
                  //replace embedded newlines with spaces
                  stOutput = stOutput.Replace(Environment.NewLine, " ");
  
                  swOut.Write(stOutput);
              }
          }
          swOut.Close();
      }
      MessageBox.Show("Data successfully saved");
  }
  </code></pre>
  
  <p>but the output is this:</p>
  
  <pre>
  0.512,45,tested_negative
  0.966,33,tested_negative
  0.42,35,tested_negative
  0.665,46,tested_positive
  0.329,29,tested_negative
  ,,
  ,,
  ,,
  ,,
  ,,
  ,,
  ,,
  ,,
  </pre>
  
  <p>The empty rows get exported too.</p>
  
  <p>How can I fix this problem?</p>