Writing information from Combo-box to text file

前提是你 提交于 2020-01-05 09:04:40

问题


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?


回答1:


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 ;-)




回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/6352588/writing-information-from-combo-box-to-text-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!