I hope the mods don't mind me titling this post mostly in German. Basically the below code is for saving and opening CSV files from and to a DataGridView.
Saving DataGridView data to a CSV file:
Finding and opening a CSV file to a DataGridView:
ChrisE informed a member about using TextFieldParser for CSV files, which I Googled and found the opening method above which was coded by David on Stack Overflow:
https://stackoverflow.com/questions/...grid-in-vb-net
I hope someone finds this useful.
Saving DataGridView data to a CSV file:
Code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
SaveFileDialog1.Filter = "CSV Files (*.csv*)|*.csv"
If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
' The DataGridView1.ClipboardCopyMode line ensures that the data stays in the correct column and row for saving without headers
DataGridView1.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableWithoutHeaderText
DataGridView1.SelectAll()
Try
IO.File.WriteAllText(SaveFileDialog1.FileName, DataGridView1.GetClipboardContent().GetText(TextDataFormat.CommaSeparatedValue))
Catch ex As Exception
MessageBox.Show("This file is open in another application. Either change the filename or close the application using the file you're trying to update.")
End Try
DataGridView1.ClearSelection()
End If
End Sub
Finding and opening a CSV file to a DataGridView:
Code:
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
OpenFileDialog1.Filter = "CSV Files (*.csv*)|*.csv"
If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
DataGridView1.Rows.Clear()
Dim TextFieldParser1 As New Microsoft.VisualBasic.FileIO.TextFieldParser(OpenFileDialog1.FileName)
TextFieldParser1.Delimiters = New String() {","}
While Not TextFieldParser1.EndOfData
Dim Row1 As String() = TextFieldParser1.ReadFields()
If DataGridView1.Columns.Count = 0 AndAlso Row1.Count > 0 Then
Dim i As Integer
For i = 0 To Row1.Count - 1
DataGridView1.Columns.Add("Column" & i + 1, "Column" & i + 1)
Next
End If
DataGridView1.Rows.Add(Row1)
End While
End If
End Sub
https://stackoverflow.com/questions/...grid-in-vb-net
I hope someone finds this useful.