What is the most suitable way to solve the problem?

HO Kwok Piu (200257110) 21 Reputation points
2020-11-22T15:33:24.517+00:00

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?

VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,564 questions
{count} votes

Accepted answer
  1. Karen Payne MVP 35,031 Reputation points
    2020-11-23T17:24:50.367+00:00

    Hello @HO Kwok Piu (200257110) ,

    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

    0 comments No comments

4 additional answers

Sort by: Most helpful
  1. Anonymous
    2020-11-23T19:01:45.707+00:00

    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
    
    0 comments No comments

  2. Hobbyist_programmer 621 Reputation points
    2020-11-25T09:55:37.713+00:00

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


  3. Anonymous
    2020-11-25T15:42:14.967+00:00

    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.

    0 comments No comments

  4. MasMin 1 Reputation point
    2022-05-30T08:55:46.713+00:00

    Find best answer at besokerja.com

    0 comments No comments