none
VB.NET | Saving ListBox with Additional information in My.settings RRS feed

  • Question

  • Hi, I recently started learning listboxes on VB.net and wanted to create something like a student list with additional information:

        Private Class Students
            Private m_Name As String
            Private m_Age As String
    
            Public Sub New(ByVal new_Name As String, ByVal _
            new_Age As String
            )
                m_Name = new_Name
                m_Age = new_Age
            End Sub
    
            Public Overrides Function ToString() As String
                Return m_Name
            End Function
    
            Public Function Age() As String
                Return m_Age
            End Function
        End Class

    So, students add to the listbox as follows:

    ListBox1.Items.Add(New Students(StudentName.Text, StudentAge.Text)) 'StudentName and  StudentAge are textboxes.

    but I also wanted to save this information so that it is automatically entered when the program is restarted. I tried to do first an event that saves every item in the ListBox but using the function above it doesn't work.

        Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
    
            For Each item In ListBox1.Items
                My.Settings.Students.Add(item)
                My.Settings.Save()
            Next
    
        End Sub

    Then I would like to load this information, but just like the event with saving information when closing the program it does not work.

        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            If My.Settings.Students Is Nothing Then
                My.Settings.Students = New Specialized.StringCollection
            Else
                For Each item In My.Settings.Students
                    ListBox1.Items.Add(item)
                Next
            End If
    
        End Sub

    • Edited by floyare Tuesday, November 26, 2019 3:28 PM
    Tuesday, November 26, 2019 3:27 PM

All replies

  • Hi

    Here is an adjusted piece of code that may be helpful.

    This example saves and loads student data from a file, and can contain as many properties as are needed. Add whatever further properties to the Class Srudent as are needed and the saving and loading will be taken care of. BE AWARE however, if you change the number of properties, then it will necessitate that any previously saved file be deleted as it wouldn't 'fit' any new Student data structure. NOTE: I made a small adjustment to the Class to encompass Properties rather than Private variables

    ' Form1 with 2 textboxes,
    ' Button1 (ADD new Student),
    ' and ListBox1 (Name/Age list)
    Option Strict Off
    Option Explicit On
    Imports System.Runtime.Serialization.Formatters.Binary
    Public Class Form1
    	Dim Students As New List(Of Student)
    	Dim BS As New BindingSource
    	' asjust path to suit
    	Dim StudentPath As String = IO.Path.Combine(My.Computer.FileSystem.SpecialDirectories.Desktop, "StudentData.dat")
    	Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
    		SaveStudents()
    	End Sub
    	Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    		LoadStudents()
    		BS.DataSource = Students
    		With ListBox1
    			.Sorted = True
    			.DataSource = BS
    			.SelectedIndex = -1
    		End With
    		StudentName.Select()
    	End Sub
    	Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    		Students.Add(New Student(StudentName.Text, StudentAge.Text))
    
    		BS.ResetBindings(False)
    
    		ListBox1.SelectedIndex =
    		ListBox1.FindStringExact(StrConv(String.Format("{0} {1} ", StudentName.Text, StudentAge.Text), vbProperCase))
    
    		StudentName.Text = Nothing
    		StudentAge.Text = Nothing
    
    	End Sub
    	Sub SaveStudents()
    		Dim fs As IO.FileStream = New IO.FileStream(StudentPath, IO.FileMode.OpenOrCreate)
    		Dim bf As New BinaryFormatter()
    		bf.Serialize(fs, Students)
    		fs.Close()
    	End Sub
    	Sub LoadStudents()
    		If FileIO.FileSystem.FileExists(StudentPath) Then
    			Students.Clear()
    			Dim fsRead As New IO.FileStream(StudentPath, IO.FileMode.Open)
    			Dim bf As New BinaryFormatter()
    			Students = CType(bf.Deserialize(fsRead), List(Of Student))
    			fsRead.Close()
    		End If
    	End Sub
    
    	' as many properties as are needed can
    	' be added To this Class And saving and
    	' loading will be taken care of,
    	<Serializable> Class Student
    		Property m_Name As String
    		Property m_Age As String
    
    		Public Sub New(ByVal new_Name As String, ByVal new_Age As String)
    			m_Name = new_Name
    			m_Age = new_Age
    		End Sub
    		Public Overrides Function ToString() As String
    			' set name(s) to ProperCase
    			Return StrConv(String.Format("{0} {1} ", m_Name, m_Age), vbProperCase)
    		End Function
    
    		Public Function Age() As String
    			Return m_Age
    		End Function
    	End Class
    End Class



    Regards Les, Livingston, Scotland


    • Edited by leshay Tuesday, November 26, 2019 6:56 PM Forgot the ListBox
    Tuesday, November 26, 2019 4:15 PM