Kuzon
Kuzon

Reputation: 822

Writing information from Combo-box to text file

I am trying to right the information from a combobox into a text file so it can be saved. If the information in the combobox is John, Marry, Jack I would like it to appear in the text file like this:

John
Mary
Jack

The code I currently use give a result of JohnMaryJack in the text file

For Each item As Object In cmbworld.Items
        Dim test As String
        test = item
        sb.AppendFormat("{0}", item)
        Dim FILE_NAME As String = "D:\Documents\test.txt"
        If System.IO.File.Exists(FILE_NAME) = True Then
            Dim objWriter As New System.IO.StreamWriter(FILE_NAME)
            objWriter.Write(test)
            objWriter.WriteLine()
            objWriter.Close()
            MsgBox("Text written to file")
        Else
            MsgBox("File Does Not Exist")
        End If

    Next

How would I fix this?

Upvotes: 1

Views: 3613

Answers (3)

Stefan
Stefan

Reputation: 11509

IO.File.WriteAllLines(filename, (From p As String In cmbworld.Items).ToArray)

Upvotes: 0

Koen
Koen

Reputation: 2571

First I would take the writing to the file out of the For Each-loop. This way you only write to the file once. Second you can slightly adapt the answer of @BiggsTRC to

sb.AppendFormat("{0} {1}", item, Environment.NewLine)

Furthermore you use the variable test to write to the textfile, instead of the stringbuilder you used. This way the formating never gets into the file.

So than your piece of code looks something like this:

Dim sb as new StringBuilder()

For Each item As Object In cmbworld.Items
        'Dim test As String
        'test = item
        sb.AppendFormat("{0} {1}", item, Environment.NewLine)
Next

Dim FILE_NAME As String = "D:\Documents\test.txt"
If System.IO.File.Exists(FILE_NAME) = True Then
    Dim objWriter As New System.IO.StreamWriter(FILE_NAME)
    objWriter.Write(sb.ToString()) 'Use the stringbuilder here
    objWriter.WriteLine()
    objWriter.Close()
    MsgBox("Text written to file")
Else
    MsgBox("File Does Not Exist")
End If

There could be some syntax-minor error in it, cause it's a long time I've written VB and I haven't a VS present at the moment, but I think you get the picture ;-)

Upvotes: 1

IAmTimCorey
IAmTimCorey

Reputation: 16757

I think you just need to change this line:

sb.AppendFormat("{0}", item)

To be like this:

sb.AppendFormat("{0}\r\n", item)

(notice the space after the {0})

This will give you a space after each person's name so that you will end up with one name per line with a return after the last line.

Upvotes: 0

Related Questions