Matti Tiira

Matti Tiira

  • NA
  • 46
  • 9.3k

Csv importing to datagridview with commas and double quotes

Mar 21 2019 4:39 AM
Hi!
 
I have made a windows forms application which I can open and modify csv files with.
I have an other program where the csv file is made with.
The problem is that the csv file has commas and double quotes as delimiters.
How can I trim the quotes so they dont appear in the datagridview?
 
Now it looks like this in my program.
 
And my code for the import looks like this:
  1. private void btnImport_Click(object sender, EventArgs e)  
  2. {  
  3. openFileDialog1.ShowDialog();  
  4. txtFilePath.Text = openFileDialog1.FileName;  
  5. BindDataCSV(txtFilePath.Text);  
  6. }  
  7. private void BindDataCSV(string filePath)  
  8. {  
  9. DataTable dt = new DataTable();  
  10. string[] lines = System.IO.File.ReadAllLines(filePath);  
  11. if (lines.Length > 0)  
  12. {  
  13. string firstLine = lines[0];  
  14. string[] headerLabels = firstLine.Split(',');  
  15. foreach (string headerWord in headerLabels)  
  16. {  
  17. dt.Columns.Add(new DataColumn(headerWord));  
  18. }  
  19. for (int r = 1; r < lines.Length; r++)  
  20. {  
  21. string[] dataWords = lines[r].Split(',');  
  22. DataRow dr = dt.NewRow();  
  23. int columnIndex = 0;  
  24. foreach (string headerWord in headerLabels)  
  25. {  
  26. dr[headerWord] = dataWords[columnIndex++];  
  27. }  
  28. dt.Rows.Add(dr);  
  29. }  
  30. }  
  31. if (dt.Rows.Count > 0)  
  32. {  
  33. dataGridView1.DataSource = dt;  
  34. }  

I would really appreciate all help, Thanks
 
-Matti

Answers (6)