Writing information from Combo-box to text file - vb.net

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?

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

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.

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

Related

new folders from a list, from a text file in vb.net

I want to be able to create new folders from a list that is stored in a text file.
The names are stored like
test1
test2
test3
so my code so far, loads the path to create the new folders, (which is the oldest folder in the given parent folder) stored in another text file "Foldercreation.txt"
then open the file with the names of the folders I want to create, "Folderstocreate.txt" and stores them all in filereader2.
but then when trying to create the folders for each line nothing happens.
My current code;
Dim fileReader, filereader2 As System.IO.StreamReader
Dim stringreader, parfolder As String
Dim path, foldername As List(Of String)
Dim count As Byte
If MsgBox("Are you sure you want to create these folders?,
Before clicking yes, make sure EVERYONE is out of paperport & you have entered the correct numbers.", MsgBoxStyle.YesNo, "WARNING!") = MsgBoxResult.Yes Then
If strnumbx.Text = "" Then
MsgBox("You have not entered a start number for the folders.", MsgBoxStyle.OkOnly, "Error")
End If
'Loads a text file at the given location, to read to.
fileReader = My.Computer.FileSystem.OpenTextFileReader("C:\Data\Test\Foldercreation.txt")
'Set stringreader as the read line from the file
stringreader = fileReader.ReadLine()
path = System.IO.Directory.GetDirectories(stringreader).ToList
path.Sort()
count = path.Count - 1
parfolder = path(count)
'System.IO.Directory.CreateDirectory(parfolder & "\test")
filereader2 = New StreamReader("C:\Data\Test\Folderstocreate.txt", True)
filereader2.ReadToEnd()
For Each line In filereader2.ReadToEnd()
System.IO.Directory.CreateDirectory(parfolder & fileReader.ReadToEnd(count - 1))
count = count + 1
Next
End If
fileReader.Close()
filereader2.Close()
This function would do it but you may want to put in some exception handling.
Directory.CreateDirectory will create all parent folders if they don't exist.
Private Sub CreateAllDirectories(ByVal strFileList As String)
Dim strDirectories As String() = File.ReadAllLines(strFileList)
For Each strDirectory As String In strDirectories
If Not Directory.Exists(strDirectory) Then
Directory.CreateDirectory(strDirectory)
End If
Next
End Sub

VB.net load controls and content from textfile to textboxes

...Hopefully this question will be readable...
I have 27 textboxes.
The controlname and the text in the textboxes are written to a textfile like this:
System.DateTime.Now.ToString("yyyyMMdd") & "_Names_Config.txt"
Dim objWriter As New System.IO.StreamWriter(configfile, True)
'Textboxes
objwriter.Writeline("tbmax1") 'Control name
objwriter.Writeline("tbmax1.text) 'The text in the textbox
objWriter.WriteLine("tbname1") 'Control name
objWriter.WriteLine(tbname1.Text) 'The text in the textbox
objWriter.WriteLine("tbext1") 'Control name
objWriter.WriteLine(tbext1.Text) 'The text in the textbox
'And so on for all the the controls
This goes on for all the textboxes and controls, so 54 lines in total.
Works great. The textfile looks like this:
Alright, now the issue. There will be a load button that should search the textfile -> find the control matching the form's control -> use the line below and fill that spesific line in the control's textbox -> then find next control and do the same.
Load button: This is #1 attempt;
'Openfiledialog, then:
Using reader As New StreamReader(OpenFileDialog1.FileName.ToString)
Dim currentTextBox As TextBox = Nothing
While reader.Peek > -1
Dim line As String = reader.ReadLine()
If Not String.IsNullOrEmpty(line) Then
Dim tmpTextbox = Controls.Find(line, True) 'Try to find text according to line
If tmpTextbox.Any() Then 'It´s a textbox name
currentTextBox = DirectCast(tmpTextbox(0), TextBox)
Else
'?
End If
End If
End While
End Using
Here comes what I don't understand at all. See before and after picture of what happens to the 27 textboxes after I load the textfile.
What it SHOULD look like:
What it will look like:
"Edit channels" is actually the title of the form itself. I'm speechless. Because I totally don't understand why this happens and the load code, I moved on to another attempt.
#2 attempt:
Using reader As New StreamReader(OpenFileDialog1.FileName)
Dim Line As String = reader.ReadLine()
Dim Current As Integer = 0
Dim TB As TextBox = Nothing
While Not IsNothing(Line) 'It will be Nothing when file is over
'__________________________________________________________________1
If Line.StartsWith("tbext1") Then
'We will increment CurrentChannel, as we changed the section
Current += 1
For onetonine = 1 To 9
tbext1.Text = Line
Next
End If
If Line.StartsWith("tbname1") Then
'We will increment CurrentChannel, as we changed the section
Current += 1
For onetonine = 1 To 9
tbname1.Text = Line
Next
End If
If Line.StartsWith("tbmax1") Then
'We will increment CurrentChannel, as we changed the section
Current += 1
For onetonine = 1 To 9
tbmax1.Text = Line
Next
End If
'__________________________________________________________________2
'Then I guess this would go on for all the 27 textboxes (probably a really bad attempt)
End While
End Using
However, this just goes into break mode.
Your first approach works already if you fill the Else part:
If tmpTextbox.Any() Then
currentTextBox = DirectCast(tmpTextbox(0), TextBox)
ElseIf currentTextBox IsNot Nothing Then
currentTextBox.Text = line
End If
But you should not use it in production code:
Control-names are a very bad key for a database record or file entry:
They can change in future and you won't notice it
They are GUI related and not supposed to be identifiers for properties
is not fail-safe because there could be multiple controls with the same name
don't store key-value pairs on different lines, that makes it difficult, less readable and more error-prone to put them together afterwards
If you want to use one line you need a delimiter that a user never enters, it can be a combination of multiple characters like |::| or something similar. Then you can later use String.Split({"|::|"}, StringSplitOptions.None) to get both tokens back.
However, this is still not a good approach and also not 100% safe. So better approaches were
serialize/deserialize a List(Of String).
If you want to store it in a way that a human can read you should prefer XML.
Here's an example how you can write/read xml easily:
' write all TextBoxes to a file '
Dim allTextBoxes = TextBoxPanel.Controls.OfType(Of TextBox)()
Dim doc As New XDocument(New XElement("Channels"))
For Each txt In allTextBoxes
doc.Root.Add(New XElement(txt.Name, txt.Text.Trim()))
Next
doc.Save(OpenFileDialog1.FileName)
' later read it ... '
Dim xml As XDocument = XDocument.Load(OpenFileDialog1.FileName)
For Each element As XElement In xml.Descendants("Channels").Descendants()
Dim txt = allTextBoxes.FirstOrDefault(function(t) t.Name = element.Name)
If txt IsNot nothing
txt.Text = element.Value
End If
Next

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

Saving Columns of listview in VB with separator

So I have a listview which has two columns. the listview view is details.
I have successfully imported a file into the list view with correct splits. The code i used is,
Using sr As StreamReader = File.OpenText( file path )
While (-1 < sr.Peek())
Dim line As String = sr.ReadLine()
Dim item As New ListViewItem(line.Split(":"c))
ListView1.Items.Add(item)
End While
sr.Close()
End Using
So this imports the lines from my file to the program into correct columns with : as split.
Now I also have a option for users to add data from my program to the file the same way, I used this code,
Using sw As StreamWriter = File.AppendText(file path)
For Each item As ListViewItem in ListView1
Dim line As String = Nothing
For Each entry As String in item.SubItems
line.Append(entry & ":")
Next For
sw.WriteLine(line)
Next For
sw.Close()
End Using
Taken from : Separating text from .txt into colums in listview (VB.net mobile)
But my bad, vb gives this error,
Error 1 Expression is of type 'System.Windows.Forms.ListView', which is not a collection type. C:\Users\xxxx\documents\visual studio 2012\xxxxx\Form1.vb 97
I am not sure why i am getting this error, is it because of my list views properties ?
I want to be able to save the data to the text file when user click a button.
This line:
For Each item As ListViewItem in ListView1
should be this:
For Each item As ListViewItem in ListView1.Items
and this line:
For Each entry As String in item.SubItems
should be this:
For Each entry As ListViewItem.ListViewSubItem in item.SubItems
You then get a String from the Text property of the subitem.

How to write textbox values to .txt file with vb.net

I have a simple form with two textboxes, I want Textbox1 to write to a file named C:\VALUE1.txt and Textbox2 to write its value to a file named C:\VALUE2.txt
Any text that is already in the text file MUST be over written.
It's worth being familiar with both methods:
1) In VB.Net you have the quick and easy My.Computer.FileSystem.WriteAllText option:
My.Computer.FileSystem.WriteAllText("c:\value1.txt", TextBox1.Text, False)
2) Or else you can go the "long" way round and use the StreamWriter object. Create one as follows - set false in the constructor tells it you don't want to append:
Dim objWriter As New System.IO.StreamWriter("c:\value1.txt", False)
then write text to the file as follows:
objWriter.WriteLine(Textbox1.Text)
objWriter.Close()
Dim FILE_NAME As String = "C:\VALUE2.txt"
If System.IO.File.Exists(FILE_NAME) = True Then
Dim objWriter As New System.IO.StreamWriter(FILE_NAME)
objWriter.Write(TextBox2.Text)
objWriter.Close()
MsgBox("Text written to file")
Else
MsgBox("File Does Not Exist")
End If
Have a look at the System.IO and System.Text namespaces, in particular the StreamWriter object.