Keep DataGridView data after closing, without database

M B 41 Reputation points
2021-05-03T09:32:45.837+00:00

Hello,
please, is there any way how to save data that are in DataGridView when it's not connected to DB?

When I close the form and open it again, it should be still the same as before closing.

I'm a noob, I finally made a form with everything that I need but need this last thing.
This is my table:

Public Class Form1

    Dim table As New DataTable("Table")

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect

        table.Columns.Add("Date", Type.GetType("System.DateTime"))
        table.Columns.Add("Code", Type.GetType("System.String"))
        table.Columns.Add("Position", Type.GetType("System.String"))
        table.Columns.Add("Note", Type.GetType("System.String"))
        table.Columns.Add("Solved", Type.GetType("System.DateTime"))

        DataGridView1.DataSource = table


    End Sub

Can anyone post me any code to do that?
Thanks

Developer technologies | Windows Forms
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 122.6K Reputation points
    2021-05-03T10:10:56.65+00:00

    Initially try a simple approach like this:

    Dim table As New DataTable("Table")
    ReadOnly p As String = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "mydata.xml")
    
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    
       DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect
    
       If Not File.Exists(p) Then
          table.Columns.Add("Date", Type.GetType("System.DateTime"))
          table.Columns.Add("Code", Type.GetType("System.String"))
          table.Columns.Add("Position", Type.GetType("System.String"))
          table.Columns.Add("Note", Type.GetType("System.String"))
          table.Columns.Add("Solved", Type.GetType("System.DateTime"))
       Else
          table.ReadXml(p)
       End If
    
       DataGridView1.DataSource = table
    
    End Sub
    
    Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
    
       table.WriteXml(p, XmlWriteMode.WriteSchema)
    
    End Sub
    
    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.