简体   繁体   中英

VB how to write listbox items to a text file

Okay so I'm creating a personal to-do list program inside of VB(Using visual studio) and I'm having trouble implementing the function where the items inside of the listbox get added to a textfile.

Here is the code I have tried:

Private Sub btnAddItem_Click(sender As Object, e As EventArgs) Handles btnAddItem.Click

    ''Adds item to the listbox.
    list.Items.Add(txtItem.Text)

    txtItem.Clear() ''Clears the textbox after adding item.
    txtItem.Select() ''Sets the cursor onto the textbox after adding item.

    Dim file As System.IO.StreamWriter
    file = My.Computer.FileSystem.OpenTextFileWriter("Test.txt", True)
    file.WriteLine(list.Items)
    file.Close()

End Sub

I have also tried; file.WriteLine(list.Items.Text) however that is not an option inside of that statement.

The button will not be how the list is saved but I'm just trying to get the test file to write properly first. The test file is created however if I type in: test 1 test 2 test 3 Into the listbox, the Test.txt file simply shows:

System.Windows.Forms.ListBox+ObjectCollection
System.Windows.Forms.ListBox+ObjectCollection
System.Windows.Forms.ListBox+ObjectCollection

Any help would be greatly appreciated!

After you have added all the items to the list box then you need to address each item individually in a loop.

Private Sub WriteListItems()
        Dim lst As String = ""
        For Each item As String In ListBox1.Items
            lst &= item & vbCrLf
        Next
        Debug.Print(lst)
End Sub

You need to loop each item in your ListBox and add them to your Test.txt . you can have it in separate method.

Private Sub putItem()
    For Each i In list.Items
        Dim file As System.IO.StreamWriter
        file = My.Computer.FileSystem.OpenTextFileWriter("Test.txt", True)
        file.WriteLine(i)
        file.Close()
    Next
End Sub

If you wish to add Item in the Test.txt every clicking the button just like in your example. you can replace your code: file.WriteLine(list.Items) to file.WriteLine(txtItem.Text) and move txtItem.Clear() to the end of the ButtonClick() so that txtItem.Text are added to file before clearing it.

list.Items.Add(txtItem.Text)

Dim file As System.IO.StreamWriter
file = My.Computer.FileSystem.OpenTextFileWriter("Test.txt", True)
file.WriteLine(txtItem.Text)
file.Close()

txtItem.Clear() ''Clears the textbox after adding item.
txtItem.Select() ''Sets the cursor onto the textbox after adding item.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM