Mathijs
Mathijs

Reputation: 65

vb.net save listbox items empty lines

I want to save listbox items to a txt file while using savefiledialog

This is the code I'm using, it's working but it will put a new line between every item. And I'd like to save without those empty lines. If anyone could help, thanks!

My code:

            If ListBox1.Items.Count > 0 Then
        SaveFileDialog1.InitialDirectory = "C:/"
        SaveFileDialog1.Title = "YOUR RESULTS"
        SaveFileDialog1.FileName = Label4.Text
        SaveFileDialog1.Filter = ("text files (*.txt) | *.txt")

        SaveFileDialog1.ShowDialog()

        Dim w As New IO.StreamWriter(SaveFileDialog1.FileName)
        Dim i As Integer
        For i = 0 To ListBox1.Items.Count - 1
            w.WriteLine(ListBox1.Items(i).ToString)
        Next
        w.Close()
    Else
        MsgBox("There is nothing to save", MsgBoxStyle.Information)
    End If

Upvotes: 2

Views: 361

Answers (1)

ElektroStudios
ElektroStudios

Reputation: 20494

To remove spaces from the start of a string, use the default String.TrimStart() extension method, as follows:

w.WriteLine(ListBox1.Items(i).ToString.TrimStart)

To remove only spaces from the end, use the default String.TrimEnd() extension method, and for remove both spaces from start and end of a string, use String.Trim()

Update

I suggest you to use a StringBuilder object as follows:

Dim sb As New StringBuilder

For Each lbItem As Object In ListBox1.Items
    sb.Append(lbItem.ToString)
Next

File.WriteAllText(SaveFileDialog1.FileName, sb.ToString, Encoding.Default)

Upvotes: 3

Related Questions