My application is suppose to save the information that I put in the application that is in a listbox in form2. All the information is in form1, but I got it to save it in the listbox in form2 and I can see it when I load up the form2. Im suppose to make 10 different list for it, (it says it should be in arrays, but I dont know how to do it) and I should be able to save them everytime I put a new one in, but when I put a new list in the listbox and close the application and then reopen it, its erased, how do I save it and keep it in the lstbox so it doesnt get erased?

Recommended Answers

All 13 Replies

See if this helps.

Public Class Form1
    Private myListBoxItemsFile As String = "C:\myListBoxItemsFile.txt" '// your file.

    '// Save to File from ListBox.
    Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        Dim myCoolWriter As New IO.StreamWriter(myListBoxItemsFile)
        For Each coolItem In ListBox1.Items '// loop thru all items in ListBox.
            myCoolWriter.WriteLine(coolItem) '// write each item to a line.
        Next
        myCoolWriter.Close() '// .Close your File writer.
    End Sub

    '// Load ListBox.
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        If IO.File.Exists(myListBoxItemsFile) Then '// check if file exists.
            ListBox1.Items.AddRange(IO.File.ReadAllLines(myListBoxItemsFile)) '// load each line as an item in the ListBox.
        End If
    End Sub
End Class

I tried to Add to add a list to the listbox and it came up in the listbox in form2, then I went back to form1 and tried to add another one, but all it did was erase the one that I just put in, then I closed it to see if it would save and it came up as an error Unauthorized AccessException was unhandled under

Dim myCoolWriter As New IO.StreamWriter(myListBoxItemsFile)

How can I add more then one list to the listbox, or do I need to use a different code to allow me to do that and what does this error message mean

Very confusing to understand.

Try my provided code in a new project with just one ListBox.
You can add a Button and a TextBox to that Form, and have in Button1.Click...

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        ListBox1.Items.Add(TextBox1.Text) '// add items to ListBox from TextBox.
    End Sub

This will add individual items to your ListBox.
Close the Form by the little "x" in the top right corner of the Form and reload project. The ListBox items will be restored.

Yes that does add it to the listbox, but mines a lil bit harder, I already have a listbox1 on my form1 and on form2 and with the code you provided it comes up on form1, but when I try to go to my form2 listbox it only has one list saved and nothing else, but if I try to add a new list it replaces the one I already have on there with the new one, it doesnt make another list on it. I cant delete listbox1 on my form1 because it comes up with errors, but where im really having trouble is the saving part, because its still coming up with the same error as I posted before, as long as I get this part to work right, ill be ok, its coming up with the error on your code, I dont know if I did something wrong but its still coming up with errors every time I close the application, please this is the main part of my application that I need to work

Quick question also, I need to make 10 list, when I do this does it make it into an array or do I need to set an array up to do that?

Member Avatar for Unhnd_Exception

Theres nothing wrong with codeorder's post. You will probably want to use that method. I'm just adding an additional method to save a listbox's ObjectCollection.

A list box can have strings or objects. This method will save any item in the items collection as long as the objects in the collection are marked as serializable.

Public Class Form1

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        'Fill the List Box with objects instead of strings.  This example will
        'use Font Objects and set the List Box Display Member to Name so it
        'Shows the name of the font.
        ListBoxFonts.Items.Clear()
        ListBoxFonts.DisplayMember = "Name"

        For Each FontFamily As FontFamily In FontFamily.Families
            If Not FontFamily.IsStyleAvailable(FontStyle.Regular) Then Continue For
            ListBoxFonts.Items.Add(New Font(FontFamily.Name, 12))
        Next

    End Sub

    Private Sub ButtonSaveObjectCollection_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonSaveObjectCollection.Click
        'Serialize the entire collection with the binary formatter.
        Dim Serializer As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
        Dim FileStream As System.IO.FileStream = New System.IO.FileStream("C:\ListBoxData.lbd", IO.FileMode.Create)

        'ListBox.ObjectCollection is not marked as Serializable but you can copy
        'the collection to an Array and do the Serializing from there.
        Dim ItemArray(ListBoxFonts.Items.Count - 1) As Object
        ListBoxFonts.Items.CopyTo(ItemArray, 0)
        Serializer.Serialize(FileStream, ItemArray)
    End Sub

    Private Sub ButtonLoadObjectCollection_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonLoadObjectCollection.Click
        'Open the file saved and Deserialize the object collection and add it to 
        'the list box.
        Dim DeSerializer As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
        Dim FileStream As New System.IO.FileStream("C:\ListBoxData.lbd", IO.FileMode.Open)

        ListBoxFonts.Items.Clear()
        ListBoxFonts.Items.AddRange(DeSerializer.Deserialize(FileStream))
    End Sub

   

    Private Sub ListBoxFonts_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListBoxFonts.SelectedIndexChanged
        'Simulation of a list box filled with objects instead of strings.
        'If your form's AutoScale mode is set to Font then the form will
        'Change sizes each time you select a different font.
        If ListBoxFonts.SelectedIndex = -1 Then Exit Sub

        'Convert the selected item to a font if it is a font and set the forms font
        'property to the selected item.
        If ListBoxFonts.SelectedItem IsNot Nothing AndAlso TypeOf ListBoxFonts.SelectedItem Is Font Then
            Me.Font = CType(ListBoxFonts.SelectedItem, Font)
        End If
    End Sub
End Class

The Save and Load buttons will work with a listbox filled with strings as well.

Im not saying that his code was wrong, for some reason it just wasn’t working, but it did stop coming up with that error with Unhnd_Exception code, but I still cant get it to save and to add more than one list to my form 2 listbox, it can be added to my form1 listbox, but not my form2, could the reason why I cant add any list to form2 listbox is because I don’t have any code for that form? My code is probably getting sloppy now, so ill post everything and if you can see whats the problem, please help me, im so close to finishing this.

Public Class Form1

    Dim motorID As String
    Dim desripition As String
    Dim iMyCoolInteger As Integer
    Dim voltage As Integer
    Dim Status As String
    Private myListBoxItemsFile As String = "C:\myListBoxItemsFile.txt"

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
      
        ListBoxFonts.Items.Clear()
        ListBoxFonts.DisplayMember = "Name"

     


    End Sub


    Private Sub ButtonSaveObjectCollection_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        'Serialize the entire collection with the binary formatter.
        Dim Serializer As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
        Dim FileStream As System.IO.FileStream = New System.IO.FileStream("C:\ListBoxData.lbd", IO.FileMode.Create)

        'ListBox.ObjectCollection is not marked as Serializable but you can copy
        'the collection to an Array and do the Serializing from there.
        Dim ItemArray(ListBoxFonts.Items.Count - 1) As Object
        ListBoxFonts.Items.CopyTo(ItemArray, 0)
        Serializer.Serialize(FileStream, ItemArray)
    End Sub

    Private Sub ListBoxFonts_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
        'Simulation of a list box filled with objects instead of strings.
        'If your form's AutoScale mode is set to Font then the form will
        'Change sizes each time you select a different font.
        If ListBoxFonts.SelectedIndex = -1 Then Exit Sub

        'Convert the selected item to a font if it is a font and set the forms font
        'property to the selected item.
        If ListBoxFonts.SelectedItem IsNot Nothing AndAlso TypeOf ListBoxFonts.SelectedItem Is Font Then
            Me.Font = CType(ListBoxFonts.SelectedItem, Font)
        End If
    End Sub

    '// Load ListBox.
    Private Sub ButtonLoadObjectCollection_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        'Open the file saved and Deserialize the object collection and add it to 
        'the list box.
        Dim DeSerializer As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
        Dim FileStream As New System.IO.FileStream("C:\ListBoxData.lbd", IO.FileMode.Open)

        ListBoxFonts.Items.Clear()
        ListBoxFonts.Items.AddRange(DeSerializer.Deserialize(FileStream))
    End Sub
    

    ' This is to actually see if the values are in the range
    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click


        btnrpm.Enabled = False
        With TextBox1
            If .Text = "" Then
                Label1.Text = ""
                Exit Sub
            End If
            If IsNumeric(.Text) Then ' if .Text is Numeric and does not contain letters.
                If .TextLength = 5 Then ' check if length is 5.
                    If CInt(.Text) >= 10000 AndAlso CInt(.Text) <= 99999 Then ' check for value, if greater/less than...
                        Label1.Text = "This is a five digit code "
                        btnrpm.Enabled = True
                    Else
                        Label1.Text = "Value must be between 10,000 and 99,999"
                    End If
                Else
                    Label1.Text = "Not a 5 digit code, please renter a new one"
                End If
            Else ' if not Numeric.
                Label1.Text = "Only Numeric values will be accepted"
            End If
        End With


    End Sub

    ' my rpm text (textbox3) and button to see if it is between the values
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnrpm.Click
        If CInt(textbox3.Text) >= 10 AndAlso CInt(textbox3.Text) <= 10000 Then
            MsgBox("Sucess: Integer is within bounds")
        Else ' if not within bounds.
            MsgBox("Fail: Integer is less than or greater than preset bounds", MsgBoxStyle.Critical)
        End If
    End Sub

    ' my voltage text (textbox4) and button to see if it is between the values 
    Private Sub btnvoltage_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnvoltage.Click
        If CInt(textbox4.Text) >= 10 AndAlso CInt(textbox4.Text) <= 500 Then
            MsgBox("Sucess: Integer is within bounds")
        Else ' if not within bounds.
            MsgBox("Fail: Integer is less than or greater than preset bounds", MsgBoxStyle.Critical)
        End If
    End Sub



    ' this is for the string to use as a desprition of the motor
    Private Sub textbox2_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles textbox2.TextChanged
        desripition = textbox2.Text
    End Sub
    ' this is for the status to see if characters are the correct ones to use or not
    Private Sub textbox5_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles textbox5.TextChanged

    End Sub

    Private Sub btnstatus_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnstatus.Click
        ' Validation for string containing: On Off Mnt Na
        If Not textbox5.Text = "ON" Then ' If textbox doesnt contain ON then
            If Not textbox5.Text = "OFF" Then ' If textbox doesnt contain OFF then
                If Not textbox5.Text = "MNT" Then ' If textbox doesnt contain MNT then
                    If Not textbox5.Text = "NA" Then ' If textbox doesnt contain NA then
                        MsgBox("Must be either: ON/OFF/MNT/NA, MsgBoxStyle.Exclamation") ' Error message displayed
                    End If
                End If
            End If
        End If
    End Sub

    ' this is to show form2
    Private Sub btnform2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnform2.Click
        Form2.Show()
        Dim sTemp As String = TextBox1.Text & ":" & textbox2.Text & ":" & textbox3.Text & ":" & textbox4.Text & ":" & textbox5.Text
        Form2.ListBoxFonts.Items.Add(sTemp) '// add to ListBox on Form2.
    End Sub



    Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        ListBoxFonts.Items.Add(TextBox1.Text) '// add items to ListBox from TextBox.
    End Sub
End Class

The button “ButtonSaveObjectCollection” doesn’t save also and the “ButtonLoadObjectCollection“ doesn’t load and the form2 button just shows the form2 with the lisbox, I hope someone could help me out and see what amader with my code, please this is due real soon and I have no idea whats amader with it

Member Avatar for Unhnd_Exception

ButtonSave Saves. ButtonLoad Loads.

I don't quite understand what you are doing.

Form1? Are the listboxes on form 1. You enter in information into the listboxes and then save them. When form1 reopens after being closed the information entered in previously will appear in form1's listboxes.

What is form2 supposed to do. Show the exact same listboxes that are on form1.

Don't quite get what is your doing with form2.

Oh sorry I keep thinking its my other thread. This is my other thread

http://www.daniweb.com/software-development/vbnet/threads/358086

and I got help from it, but now I need specifically help on the save and load part, thats why I made this one. What im suppose to do is make an apllication that has all of these (which theve all been done and coded

MotorID: Five-digit string, such as "02340"
Description: String
RPM: Integer, values in the range of 10 to 10000
Voltage: Integer, values in the range of 1 to 500
Status: String, three characters

The status values are
ON: Motor is online and running
OFF: Motor is online, but not running
MNT: Motor is undergoing maintenance and cleaning
NA: Motor is not available

But the reason I made this thread was how do I save the listboxes on my form2. When I add something to the listbox its suppose to save and go to my form2 and have everything loaded up there and I dont know why it never works. There is a listbox on form1 and form2, and the listbox on form1, when I add a list to it itll add it to the form1 listbox, but when I go to listbox on my form2 it only shows one list, even if I add multiple list to the form1 listbox. I need to save 10 different motorID's. Thats why I really need it to save and load up fine with all the info that was added threw the textboxes

What my form2 listbox is only suppose to do is just show the list that I added and thats all

You keep saying that you need Form2's ListBox to save and load the items in it, but have you tried adding Form2. infront of the ListBox1 of my first post to this thread? For Each coolItem In Form2.ListBox1.Items '// loop thru all items in ListBox. for saving, and for loading Form2.ListBox1.Items.AddRange(IO.File.ReadAllLines(myListBoxItemsFile)) '// load each line as an item in the ListBox. ?

Have you tried adding the code I supplied to Form2?

codeorder this is the problem I keep coming up with, with using your code, i dont know why, so because of this I cant use your code or use your changes

Member Avatar for Unhnd_Exception

Why don't you use your own code. Thats what I do.


If I was you I would uninstall visual studio. Maybe you should look into Majoring in Insurance, Marketing, Theater, or even Physical Education. I don't think programming is for you. Lets face it, Its not for everyone.

You have had plenty of help on this. If you need more help, maybe you should go ask your all knowing professor or maybe go and by a book on it.

Oh and by the way. Don't post on here that my code doesn't work. Maybe you should figure out how works before you use it. It works just fine. Please provide your ultimate code that does work.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.