question

HOKwokPiu200257110-7756 avatar image
0 Votes"
HOKwokPiu200257110-7756 asked ·

What is the most suitable way to solve the problem?

I am a VB begainer, and I have a question for storing data: I have designed a form which is a calculator for scoring marks, because it is a practice from my school so there are some rules for the calculator, it has to save a name in the listbox every time that the record is confirm which is I have already done.
And I want to store those records into an array or some functions that I can store temporary and retrieve later. Is there any functions in VB can virtulize?

dotnet-visual-basic
· 1
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hi @HOKwokPiu200257110-7756 ,

I want to store those records into an array or some functions that I can store temporary and retrieve later.

Did you consider saving records into database or text file?


0 Votes 0 ·
karenpayneoregon avatar image
0 Votes"
karenpayneoregon answered ·

Hello @HOKwokPiu200257110-7756,

A simplistic solution if the intent is to remember information between sessions and quick-n-easy way is to use a json file. Note there are other options e.g. saving to a text delimited file or xml while the following is strongly typed and a better solution.

In the following GitHub repository I've created a conceptual/working code sample meaning it demonstrates reading/writing to the json file and has comments.
https://github.com/karenpayneoregon/visual-basic-getting-started/tree/master/BasicJson_1

 [
   {
     "Name": "First item",
     "Value": 11.34
   },
   {
     "Name": "Secondt item",
     "Value": 1.33
   }
 ]

Class for storing data

 Imports System.ComponentModel
 Imports System.Runtime.CompilerServices
    
 Namespace Classes
     Public Class ApplicationStorage
         Implements INotifyPropertyChanged
         Private _name As String
         Private _value As Decimal
    
         Public Property Name() As String
             Get
                 Return _name
             End Get
             Set
                 _name = value
                 OnPropertyChanged()
             End Set
         End Property
    
         Property Value() As Decimal
             Get
                 Return _value
             End Get
             Set
                 _value = value
                 OnPropertyChanged()
             End Set
         End Property
    
         Public Overrides Function ToString() As String
             Return Name
         End Function
         Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged
         Protected Overridable Sub OnPropertyChanged(<CallerMemberName> Optional memberName As String = Nothing)
             RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(memberName))
         End Sub
     End Class
 End Namespace


File operations class

 Imports System.IO
 Imports Newtonsoft.Json
    
 Namespace Classes
     Public Class FileOperations
         Public Shared FileName As String = "appSetting.json"
         Public Shared Sub Save(storageList As List(Of ApplicationStorage))
             Using streamWriter = File.CreateText(FileName)
    
                 Dim serializer = New JsonSerializer With {.Formatting = Formatting.Indented}
                 serializer.Serialize(streamWriter, storageList)
    
             End Using
    
         End Sub
         Public Shared Function Load() As List(Of ApplicationStorage)
    
             Using streamReader = New StreamReader(FileName)
                 Dim json = streamReader.ReadToEnd()
                 Return JsonConvert.DeserializeObject(Of List(Of ApplicationStorage))(json)
             End Using
    
         End Function
    
     End Class
 End Namespace

Form code

 Imports System.ComponentModel
 Imports System.IO
 Imports BasicJson_1.Classes
    
 Public Class Form1
     ''' <summary>
     ''' Storage container for ApplicationStorage data.
     ''' Using a BindingList and implementing INotifyPropertyChanged interface
     ''' permits real time updates to ListBox.
     ''' </summary>
     Private bindingList as new BindingList(Of ApplicationStorage)
     ''' <summary>
     ''' Load from file if exists
     ''' </summary>
     ''' <param name="sender"></param>
     ''' <param name="e"></param>
     Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles Me.Shown
    
         If File.Exists(FileOperations.FileName) Then
    
             Try
                 bindingList = New BindingList(Of ApplicationStorage)(FileOperations.Load())
             Catch ex As Exception
                 MessageBox.Show($"Failed to load json{Environment.NewLine}{ex.Message}")
             End Try
         End If
    
         ListBox1.DataSource = bindingList
    
     End Sub
    
     ''' <summary>
     ''' Add new item if name is value and a valid decimal was entered
     ''' </summary>
     ''' <param name="sender"></param>
     ''' <param name="e"></param>
     Private Sub AddButton_Click(sender As Object, e As EventArgs) Handles AddButton.Click
         Dim value as Decimal = 0
    
         if Decimal.TryParse(ValueTextBox.Text, value) AndAlso Not string.IsNullOrWhiteSpace(NameTextBox.Text)
             bindingList.Add(new ApplicationStorage() With{.Name = NameTextBox.Text, .Value = value})
         End If
    
     End Sub
     ''' <summary>
     ''' Save items to json
     ''' </summary>
     ''' <param name="sender"></param>
     ''' <param name="e"></param>
     Private Sub SaveAllButton_Click(sender As Object, e As EventArgs) Handles SaveAllButton.Click
         if bindingList.Count >0
             FileOperations.Save(bindingList.ToList())
         End If
     End Sub
     ''' <summary>
     ''' Get current item
     ''' </summary>
     ''' <param name="sender"></param>
     ''' <param name="e"></param>
     Private Sub CurrentButtonButton_Click(sender As Object, e As EventArgs) Handles CurrentButton.Click
         if bindingList.Count >0
             if ListBox1.SelectedIndex > -1
                 Dim currentItem = bindingList.Item(ListBox1.SelectedIndex)
                 MessageBox.Show($"Name: {currentItem.Name} Value: {currentItem.Value}")
             End If
         End If
    
     End Sub
 End Class

Screen shot
41972-j1.png








j1.png (12.1 KiB)
·
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

$$ANON_USER$$ avatar image
0 Votes"
$$ANON_USER$$ answered ·

Hi

A simple example - Karens post is much more detailed.



 Option Strict On
 Option Explicit On
 Public Class Form1
 ' crrate the datatable variable
 Dim dt As New DataTable("MyTable")
    
          ' make a path to store/retrieve data
          ' here, using a system method to make
          ' the path in a safe way (to the DeskTop)
          Dim path As String = IO.Path.Combine(My.Computer.FileSystem.SpecialDirectories.Desktop, "MyDataTableData.xml")
          Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
              ' every time you close the application
              ' the datatable data will be saved.
              dt.WriteXml(path)
          End Sub
          Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
              With dt
                  ' create the columns required in
                  ' the datatable
                  .Columns.Add("ID", GetType(Integer))
                  .Columns.Add("Name", GetType(String))
                  .Columns.Add("Date", GetType(DateTime))
                  .Columns.Add("Other", GetType(String))
                  .Columns.Add("Notes", GetType(String))
            
                  If IO.File.Exists(path) Then
                      ' found a datafile, so read it into
                      ' the datatable
                      .ReadXml(path)
                  End If
              End With
              ' put the data into a DataGridView
              ' where changes made will be reflected
              ' in the datatable - keeping everything
              ' in sync.
              DataGridView1.DataSource = dt
          End Sub
      End Class

·
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hobbyistprogrammer-7674 avatar image
0 Votes"
Hobbyistprogrammer-7674 answered ·

Hallo All, Which is faster for reading data into program XML or Jason ? any difference?

· 1 ·
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Seems that this should be a separate question.

0 Votes 0 ·
$$ANON_USER$$ avatar image
0 Votes"
$$ANON_USER$$ answered ·

Hi
Using XML or JSON for storage should have minimal difference. If you are dealing with huge amounts of data then there may be some small difference.
You could mock up a test for each using the same data and use a timing loop to check on timings.

·
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.