-
Nov 10th, 2020, 06:16 PM
#1
Thread Starter
Hyperactive Member
How To Save and Load Text File From and To DataGridView
Hello I need to save all content of my datagridview control and then load all this data back into the control again when needed.
How can I do this? Would using StreamWriter be best for saving the data from datagridview to a text file and then read it back with StreamReader?
-
Nov 10th, 2020, 08:03 PM
#2
Re: How To Save and Load Text File From and To DataGridView
Never heard of anyone using a StreamWriter for saving and loading DataGridView data. Just get the directory and filename from SaveFileDialog and OpenFileDialog, and use this info to save your data with IO.File.WriteAllText, and open each line of data from your DAT file with My.Computer.FileSystem.ReadAllText.
Google search "datagridview save load data vb". Once you get the saving and loading down, you'll should easily be able to incorporate the save and open file dialogs with this.
Last edited by Peter Porter; Nov 10th, 2020 at 08:23 PM.
-
Nov 10th, 2020, 10:33 PM
#3
Thread Starter
Hyperactive Member
Re: How To Save and Load Text File From and To DataGridView
Thanks Peter, ok I will try to use WriteAllText but I would like to write a Sub in my module for each Save and Load.
I would like to use standard format .CSV Files for these but need some help figuring things out with it if anyone can try to help me with these Subs..?
I could use SaveFileDialog/OpenFileDialog, but for now I would like to just be able to Save/Load To and From The App Directory > Folder/File without the use of the dialogs.
I am not really sure where I need to start with it..
Code:
Public Sub DataGridView_Save_CSV()
'Saves All Data From DataGridView To .CSV Format Text File
End Sub
Code:
Public Sub DataGridView_Load_CSV()
'Loads All Data To DataGridView From A .CSV Format Text File
End Sub
I know it's not much of anything and laughable but I don't know how to begin this..
Any advice on how to begin these subs is very much appreciated.
~Thanks
Last edited by DreamWarrior77; Nov 10th, 2020 at 10:37 PM.
-
Nov 10th, 2020, 11:33 PM
#4
Re: How To Save and Load Text File From and To DataGridView
If you're not wedded to a specific format for the text file, the simplest option would be to use the ReadXml and WriteXml methods of the DataTable class. You can then bind the DataTable to the grid and everything else is automatic. It's probably five lines of code in total. XML is more verbose than CSV but is still human-readable and -editable. Some might argue more so.
If you do want to stick with a CSV format, use a TextFieldParser to read the data. You can process it as you read it and populate either a grid directly or, preferably, a DataTable that you bind. Writing could then be something like this:
vb.net Code:
File.WriteAllLines(filePath, myDataTable.Rows.Cast(Of DataRow).Select(Function(row) String.Join(",", row.ItemArray)))
-
Nov 11th, 2020, 01:03 AM
#5
Re: How To Save and Load Text File From and To DataGridView
I agree with JMC, try it out with XML
here a small sample
Code:
Public Class Form2
Private dt As New DataTable("myUsers")
Private bs As New BindingSource
Private Sub Form2_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
'save the Data when you close the Form
Me.Validate()
bs.EndEdit()
dt.WriteXml("E:\Test.xml")
End Sub
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
' your columns
dt.Columns.Add("Firstname", GetType(System.String))
dt.Columns.Add("LastName", GetType(System.String))
dt.Rows.Add("John", "Doe")
' XML load
If IO.File.Exists("E:\Test.xml") Then
dt.ReadXml("E:\Test.xml")
End If
' bind Datatable-Bindingsource
bs.DataSource = dt
' bind Textboxes
Me.DataGridView1.DataSource = bs
Me.TextBox1.DataBindings.Add("Text", bs, "Firstname")
Me.TextBox2.DataBindings.Add("Text", bs, "Lastname")
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
' add new line in Datagridview for Input
bs.AddNew()
End Sub
End Class
to hunt a species to extinction is not logical !
since 2010 the number of Tigers are rising again in 2016 - 3900 were counted. with Baby Callas it's 3901, my wife and I had 2-3 months the privilege of raising a Baby Tiger.
-
Nov 11th, 2020, 04:46 AM
#6
Re: How To Save and Load Text File From and To DataGridView
Another simple way of doing it:
For the below code your project is gonna need 2 buttons, and SaveFileDialog and OpenFileDialog from the toolbox.
Code:
Private Sub SaveButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveButton.Click
SaveFileDialog1.Filter = "DAT Files (*.dat*)|*.dat"
If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK _
Then
' The DataGridView1.ClipboardCopyMode line ensures data stays in the correct column and row for saving
DataGridView1.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableWithoutHeaderText
DataGridView1.SelectAll()
IO.File.WriteAllText(SaveFileDialog1.FileName, DataGridView1.GetClipboardContent().GetText.TrimEnd)
DataGridView1.ClearSelection()
End If
End Sub
Private Sub OpenButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenButton.Click
OpenFileDialog1.Filter = "DAT Files (*.dat*)|*.dat"
If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK _
Then
DataGridView1.Rows.Clear()
For Each Line In My.Computer.FileSystem.ReadAllText(OpenFileDialog1.FileName).Split(Environment.NewLine)
DataGridView1.Rows.Add(Split(Line, ControlChars.Tab))
Next
End If
End Sub
Everyone forgive me for doing his homework.
Last edited by Peter Porter; Nov 11th, 2020 at 05:10 AM.
-
Nov 11th, 2020, 10:44 AM
#7
Thread Starter
Hyperactive Member
Re: How To Save and Load Text File From and To DataGridView
Thanks for your responses ok well I don't want to use XML, DAT Files, CopyClipBoard or a Binding Source.
I just want to Save/Load CSV Files via these Public Subs
I would like to do this a certain way for my needs.
Ok I am just trying to experiment with it but I am getting this error when trying this method below.
System.InvalidCastException: 'Conversion from type 'DataGridViewRow' to type 'String' is not valid.'
Code:
Public Sub DataGridView_Save_CSV(Directory As String, DataGrid As DataGridView)
'Saves All Data From DataGridView To .CSV Format Text File
Dim sb As New System.Text.StringBuilder()
For Each o As Object In DataGrid.Rows
sb.AppendLine(o)
Next
System.IO.File.WriteAllText(Directory, sb.ToString)
End Sub
What do I need to do to validate this code?
-
Nov 11th, 2020, 11:24 AM
#8
Re: How To Save and Load Text File From and To DataGridView
to hunt a species to extinction is not logical !
since 2010 the number of Tigers are rising again in 2016 - 3900 were counted. with Baby Callas it's 3901, my wife and I had 2-3 months the privilege of raising a Baby Tiger.
-
Nov 11th, 2020, 05:23 PM
#9
Re: How To Save and Load Text File From and To DataGridView
Originally Posted by DreamWarrior77
Thanks for your responses ok well I don't want to use XML, DAT Files, CopyClipBoard or a Binding Source.
I just want to Save/Load CSV Files via these Public Subs...
This is one way to save your data as a CSV file:
Code:
' 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()
IO.File.WriteAllText(DirectoryAndFilename, DataGridView1.GetClipboardContent().GetText(TextDataFormat.CommaSeparatedValue))
DataGridView1.ClearSelection()
Thanks to jmcilhinney, opening a CSV file to a DataGridView can be done like this:
Code:
DataGridView1.Rows.Clear()
Dim TextFieldParser1 As New Microsoft.VisualBasic.FileIO.TextFieldParser(DirectoryAndFilename)
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
I found the opening part at this link:
https://stackoverflow.com/questions/...grid-in-vb-net
If you need to find the directory where to save the CSV file, you can do it with the SaveFileDialog:
Code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
SaveFileDialog1.Filter = "CSV Files (*.csv*)|*.csv"
SaveFileDialog1.FileName = ""
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 the CSV file to open into the DataGridView can be done with the OpenFileDialog:
Code:
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
OpenFileDialog1.Filter = "CSV Files (*.csv*)|*.csv"
OpenFileDialog1.FileName = ""
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
Last edited by Peter Porter; Nov 16th, 2020 at 06:01 PM.
-
Nov 15th, 2020, 09:29 PM
#10
Thread Starter
Hyperactive Member
Re: How To Save and Load Text File From and To DataGridView
ok Thanks for all the examples ok well I have a question about the ClipboardCopyMode..
I am assuming that using this code will over write anything previously copied to my clipboard which is why I did not want to use this method.
I always use copy to clipboard for things and this would just get me upset if it kept erasing the contents of it.
So does this ClipboardCopyMode method overwrite my clipboard or does this somehow temporarily overwrite it just for the function and then somehow just place back what was originally copied to it?
-
Nov 15th, 2020, 10:55 PM
#11
Thread Starter
Hyperactive Member
Re: How To Save and Load Text File From and To DataGridView
Ideally I would like to create 2 subs, 1 for Save, 1 for Load.. both .CSV files with and without headers and by that I mean to have a boolean in the sub that can On/Off the ability to use the CSV headers or not.
So I would need FilePath and the Boolean but I need some help with these:
I would do something like this inside the Save and Load buttons
SaveCSV_DGV
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
' Call Sub
' SaveDataGridView(DataGrid as DataGridView, FilePath as String, Boolean For CSV Headers True/False)
End If
End Sub
I forget exactly how to use boolean in the subs I remember that it's either true or false for the option that you program into your subs.
If someone can refresh me on this I would appreciate it.
I will need some guidance on how I can program these..
ok then the same type of thing for OpenCSV_DGV
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
' Call Sub
' LoadDataGridView(DataGrid as DataGridView, FilePath as String, Boolean For CSV Headers True/False)
End If
End Sub
-
Nov 15th, 2020, 11:23 PM
#12
Re: How To Save and Load Text File From and To DataGridView
Originally Posted by DreamWarrior77
I forget exactly how to use boolean in the subs
No you don't. What do you think you're doing here?
Originally Posted by DreamWarrior77
Code:
If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
That says "if it is true that one value is equal to another value then". You already asked about If statements elsewhere and had it explained to you. A Boolean is a Boolean, whether it's a literal, a variable or an expression.
-
Nov 16th, 2020, 12:11 AM
#13
Thread Starter
Hyperactive Member
Re: How To Save and Load Text File From and To DataGridView
ok I am sorry for that line I just assumed the line that Peter has added was the way I needed to use the dialog for some reason I just assume things when I should not but I get overwhelmed easily.
Personally I would have just done this and then tried to add to it:
Code:
OpenFileDialog1.ShowDialog()
I have used it like this before and I am not saying it is correct but..
Why was it fine for Peter to use it? I am not understanding, please explain.
Thank You
so you are saying that I should use it like
Code:
If OpenFileDialog.ShowDialog = True Then
which would have been more appropriate to use since it cuts out unnecessary code?
or that I don't require the If statement at al in which it would just be
Code:
OpenFileDialog.ShowDialog
which brings me right back to how I would have done it.
I am sorry my mind has been very scatter brained and I have some difficulties.
Do I not want to check if the File Dialog has Opened Correctly? and just ShowDialog?
-
Nov 16th, 2020, 01:58 AM
#14
Re: How To Save and Load Text File From and To DataGridView
It's not about whether the dialogue has opened correctly. It's about what action the user took in the dialogue. The ShowDialog method returns a DialogResult value. There may be times when you don't care what that value is but, when you display an OpenFileDialog, the user can select a file and click OK or they can click Cancel. It should be obvious that you only want to use the FileName property if the user clicked OK, so you need to test whether ShowDialog returned DialogResult.OK and then act only if it did.
All operators produce a value. What would be the point if they didn't? The equality operator produces a Boolean value, i.e. True if the two values are equal and False if they aren't. In this case, you only want to use the FileName if it is True that the value returned by ShowDialog is equal to OK.
It seems to me that far too many people treat programming as though it exists in a vacuum and is divorced from the basic logic we all use every day. It's not. It's simply a formalisation of that same logic. Let's say that I said to you "if you're going to the shop, I'm going too" would you find that hard to comprehend? Of course not. What is that saying though? It's saying that if "you are going to the shop" is a true statement then the action "I'm going too" will be performed but if it's a false statement then the action will not be performed:
vb.net Code:
If you.IsGoingToShop Then
me.GoToShop()
End If
Simple, basic logic.
This code:
vb.net Code:
If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
could be written like this:
vb.net Code:
Dim result As DialogResult = OpenFileDialog1.ShowDialog
If result = Windows.Forms.DialogResult.OK Then
or like this:
vb.net Code:
Dim result As DialogResult = OpenFileDialog1.ShowDialog
Dim wasOkClicked As Boolean = (result = Windows.Forms.DialogResult.OK)
If wasOkClicked Then
A Boolean is a Boolean, just as an Integer is an Integer, whether it's a literal, a variable or an expression.
-
Nov 16th, 2020, 05:36 AM
#15
Re: How To Save and Load Text File From and To DataGridView
Edited my code above.
Fixed it so that the file name field is blank when SaveFileDialog or OpenFileDialog opens.
Last edited by Peter Porter; Nov 16th, 2020 at 06:12 PM.
-
Nov 16th, 2020, 07:40 PM
#16
Thread Starter
Hyperactive Member
Re: How To Save and Load Text File From and To DataGridView
Yes even though the user is going to select a file anyway we would not want it to say OpenFileDialog/SaveFileDialog in the file name space.. Thanks for this..
jmcilhinney I am not sure I get it fully why this is not ok:
Code:
If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
and this is better
Code:
Dim result As DialogResult = OpenFileDialog1.ShowDialog
If result = Windows.Forms.DialogResult.OK Then
the first example seems faster and neater to write but is it wrong to do it this way somehow?
Why is the second code example better to do it that way?
the third example, I want to ask you about, you declare the variable wasOkClicked as Boolean but why use a boolean here though?
Not sure I am getting this one, aren't we complicating the code unnecessarily? from the other 2 examples?
What is the advantage of the third code example? or is this just another way you can choose to do it.
I like to have a reason to do things so that is why I am asking about it.
Code:
Dim result As DialogResult = OpenFileDialog1.ShowDialog
Dim wasOkClicked As Boolean = (result = Windows.Forms.DialogResult.OK)
If wasOkClicked Then
also you said:
It's about what action the user took in the dialogue.
how many actions are there is an Open or Save File Dialog? I thought you can really only click ok or cancel..
What other actions could users take on these dialogs?
What does DialogResult.Ok mean? does that mean that it displayed the dialog with no error meaning the window/form of the dialog? or that the user has clicked Open/Save buttons successfully?
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|