I have a listbox and would like to save the items added/deleted when the form closes.

any ideas?

Recommended Answers

All 4 Replies

In formClosing event just use a loop

Dim sw As New System.IO.StreamWriter("Path for the file like C:\abc.txt")
For i As Integer=0 To Listbox1.Items.Count-1
sw.WriteLine(Listbox1.Items.Item(i))
Next
sw.Dispose()

I have a listbox and would like to save the items...

Save them where? To a database, to excel, to text file,..?

If so, here`s an exampe:

Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs)
	Dim filePath As String = "C:\Myfile.txt"
	'use your path!
	If Not File.Exists(filePath) Then
		Dim fs As FileStream = File.Create(filePath)
		fs.Close()
	End If
	Using fs As New FileStream(filePath, FileMode.CreateNew, FileAccess.Write)
		Using sw As New StreamWriter(fs)
			For Each item As String In listBox1.Items
				sw.WriteLine(item)
			Next
		End Using
	End Using
End Sub

Thanks mitja bonca! your code helped a lot. I was also wondering if i would be able have the saved items as a way to "login" to my program. in the first form (form1) i have a masked textbox and a button. you type your "pin" into the masked textbox and click the button to enter. i would like to check the masked textbox against listbox for a correct "pin". my code for that is:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        If Form4.ListBox1.Items.Contains(MaskedTextBox1.Text) Then
            Button3.Visible = True
            Button3.Enabled = True
        Else
            MsgBox("Your Pin was incorrect. Please try again.")
            Button3.Visible = False
            Button3.Enabled = False
            MaskedTextBox1.Text = ""
        End If
    End Sub

I cant check the masked textbox against the other form (form4) to have the "pins" in the listbox to work when saved with this cods:

Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs)
	Dim filePath As String = "C:\Myfile.txt"
	'use your path!
	If Not File.Exists(filePath) Then
		Dim fs As FileStream = File.Create(filePath)
		fs.Close()
	End If
	Using fs As New FileStream(filePath, FileMode.CreateNew, FileAccess.Write)
		Using sw As New StreamWriter(fs)
			For Each item As String In listBox1.Items
				sw.WriteLine(item)
			Next
		End Using
	End Using
End Sub

any ideas on how to fix this?

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.