Advertisement
perjespersson

.csvcvcv

Oct 8th, 2019
215
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.01 KB | None | 0 0
  1. private void button1_Click(object sender, EventArgs e)
  2. {
  3.  
  4. saveFileDialog1.ShowDialog();
  5. string path = saveFileDialog1.FileName;
  6.  
  7. label1.Text = saveFileDialog1.FileName;
  8.  
  9.  
  10.  
  11. if(path != "") //Om vi cancel i savedialog ska vi ej skapa filen
  12. {
  13. string csv = "";
  14. //; i Sverige, olika för olika länder?
  15. foreach (DataGridViewColumn column in dataGridView1.Columns)
  16. {
  17. csv += column.HeaderText + ';';
  18. }
  19.  
  20. //Add new line.
  21. csv += "\n";
  22.  
  23. //Adding the Rows
  24. foreach (DataGridViewRow row in dataGridView1.Rows)
  25. {
  26. foreach (DataGridViewCell cell in row.Cells)
  27. {
  28. if(cell.Value == null) // Tar man bort all text från "Comment" returnerar den null istället för ""
  29. {
  30. csv += "" + ';';
  31. }
  32. else
  33. {
  34. csv += cell.Value.ToString() + ';';
  35. }
  36.  
  37. }
  38.  
  39. //Add new line.
  40. csv += "\n";
  41. }
  42.  
  43. if (path.Substring(path.Length - 4) == ".csv") // Så att filnamnet ej blir .csv.csv när man klickar på en gammal fil i SaveDialog
  44. path = path.Remove(path.Length - 4);
  45. try
  46. {
  47. File.WriteAllText(path + ".csv", csv);
  48. }
  49. catch(System.IO.IOException)
  50. {
  51. MessageBox.Show("You can't save the file because it is being used by another program");
  52. }
  53.  
  54. saveFileDialog1.FileName = ""; // Reset, annars kommer den spara fastän vi klickar cancel
  55. }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement