2 Replies - 320 Views - Last Post: 24 April 2014 - 10:18 AM Rate Topic: -----

#1 blacksaibot  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 20
  • Joined: 04-March 14

Writing to CSV file thrown off by quotes

Posted 24 April 2014 - 08:51 AM

When one of the cells in my DGV contains quotes, it throws off the data in the CSV file by splitting the string into seperate columns.

foreach (DataGridViewRow row in dgv_NewData.Rows)
{
    if (!row.IsNewRow)
    {
        for (int i = 0; i < row.Cells.Count; i++)
        { 
sb.Append(row.Cells[i].Value + ","); 
            var value = row.Cells[i].Value.ToString();

            var append = value.Contains(",")
                     ? string.Format("\"{0}\"", value)
                     : value;

            sb.Append(string.Format("{0}", append) + ",");
        }

        sb.Append(Environment.NewLine);
    }
}




private void exportFileBrowser(StringBuilder sb)
{    StreamWriter sw;
    SaveFileDialog sfd = new SaveFileDialog();
    sfd.Filter = "CSV files (*.csv)|*.csv";
    sfd.InitialDirectory = dbDir;
    if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
    {
        sw = new StreamWriter(sfd.FileName, false)        using (sw)
        { sw.WriteLine(sb.ToString()); }

        MessageBox.Show("CSV file saved.");
    }
}


Is This A Good Question/Topic? 0
  • +

Replies To: Writing to CSV file thrown off by quotes

#2 Curtis Rutland  Icon User is offline

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4437
  • View blog
  • Posts: 7,713
  • Joined: 08-June 10

Re: Writing to CSV file thrown off by quotes

Posted 24 April 2014 - 09:23 AM

You need to escape the quotes. Here's a good thread that might help:

http://stackoverflow...g-to-csv-format
Was This Post Helpful? 0
  • +
  • -

#3 blacksaibot  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 20
  • Joined: 04-March 14

Re: Writing to CSV file thrown off by quotes

Posted 24 April 2014 - 10:18 AM

View PostCurtis Rutland, on 24 April 2014 - 09:23 AM, said:

You need to escape the quotes. Here's a good thread that might help:

http://stackoverflow...g-to-csv-format


Thanks!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1