To explain How to Save ListBox Items to Text File using OpenFile Dialog I will use 3 buttons and 1 ListBox.
- Button1 = Add items
- Button2 = Save ListBox items
- Button3 = Read Text File
- ListBox
Above Public Class Form1 we put the bellow code:
Imports System.IO
Button1 code = Add items:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ListBox1.Items.Add("item 1")
ListBox1.Items.Add("item 2")
ListBox1.Items.Add("item 3")
ListBox1.Items.Add("item 4")
ListBox1.Items.Add("item 5")
ListBox1.Items.Add("item 6")
ListBox1.Items.Add("item 7")
End Sub
Button2 code = Save ListBox Items:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim SaveFileDialog1 As New SaveFileDialog
SaveFileDialog1.FileName = ""
SaveFileDialog1.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"
If SaveFileDialog1.ShowDialog() = DialogResult.OK Then
Dim sb As New System.Text.StringBuilder()
For Each o As Object In ListBox1.Items
sb.AppendLine(o)
Next
System.IO.File.WriteAllText(SaveFileDialog1.FileName, sb.ToString())
End If
End Sub
This code actually is rewriting the Text File if it contains some data. In one of my next posts I will include a code for Appending.
Button3 code = Read Text File
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim OpenFileDialog1 As New OpenFileDialog
OpenFileDialog1.FileName = ""
OpenFileDialog1.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"
If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
Dim lines = File.ReadAllLines(OpenFileDialog1.FileName)
ListBox1.Items.Clear()
ListBox1.Items.AddRange(lines)
End If
End Sub