LukmanH LukmanH - 6 months ago 122
Vb.net Question

Vb.net Save data from datagridview to txt and load it

i'am new programmer and just studying about Visual Basic, and to complete my exams
The Data i have


Tool_1 screwdriver

Tool_2 screw

Tool_3 Magnet


And many more

i've create project, it have Data Grid View(two columns, Tools & Names) and two Button(btSave & btOpen)

i just try it with this code

Private Sub btSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btSave.Click
SaveGridData(DataGridView1, ThisFilename)
End Sub
Private Sub SaveGridData(ByRef ThisGrid As DataGridView, ByVal Filename As String)
ThisGrid.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableWithoutHeaderText
ThisGrid.SelectAll()
IO.File.WriteAllText(Filename, ThisGrid.GetClipboardContent().GetText.TrimEnd)
ThisGrid.ClearSelection()
End Sub
Private Sub btOpen_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btOpen.Click
LoadGridData(DataGridView1, ThisFilename)
End Sub

Private Sub LoadGridData(ByRef ThisGrid As DataGridView, ByVal Filename As String)
ThisGrid.Rows.Clear()
For Each THisLine In My.Computer.FileSystem.ReadAllText(Filename).Split(Environment.NewLine)
ThisGrid.Rows.Add(Split(THisLine, " "))
Next
End Sub


When i save the file it's no problem the txt file is ok, but when i want to load Text "Tool_1 Screwdriver" is not split but is in "Tools" Column

there is a solution to this ?

Answer

use this insetad of your loop in loadgriddata

For Each THisLine In My.Computer.FileSystem.ReadAllText(Filename).Split(Environment.NewLine)
dim str as string()
str=thisline.split(" ")
ThisGrid.Rows.Add(str(0),str(1))
Next

hope it helps.

Comments