VB Populating ComboBox with specific field from comma-delimited txt file - vb.net

Need to populate NameComboBox from a comma-delimited txt file. Want user to be able to select just the name from NameComboBox dropdown and the rest of the textboxes to fill in.
Right now the entire record is populating the ComboBox.
Imports System.IO
Public Class LookupForm
Private Sub LookupForm_Load(sender As Object, e As System.EventArgs) Handles Me.Load
' Load the items into the NameComboBox list.
Dim ResponseDialogResult As DialogResult
Dim NameString As String
Try
' Open the file.
Dim ContactInfoStreamReader As StreamReader = New StreamReader("TextFile.txt")
' Read all the elements into the list.
Do Until ContactInfoStreamReader.Peek = -1
NameString = ContactInfoStreamReader.ReadLine()
NameComboBox.Items.Add(NameString)
Loop
' Close the file.
ContactInfoStreamReader.Close()
Catch ex As Exception
' File missing.
ResponseDialogResult = MessageBox.Show("Create a new file?", "File Not Found",
MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If ResponseDialogResult = Windows.Forms.DialogResult.No Then
' Exit the program.
Me.Close()
End If
End Try
End Sub
****Update 11/2/15:
The names are appearing in the NamesComboBox as they should but when one is selected the info doesn't show in the other text boxes. Also as soon as form loads its already putting info in the other textboxes (from the 1st record in the array) before any name is selected from NamesComboBox.
Heres my streamwrite form
Imports System.IO
Public Class ContactInfoForm
' Declare module-level variable.
Private ContactInfoStreamWriter As StreamWriter
Private Sub SaveButton_Click(sender As System.Object, e As System.EventArgs) Handles SaveButton.Click
' Save the users contact information to the end of the file.
' Make sure name field and at least 1 number field is not empty.
If NameTextBox.Text <> "" And PhoneNumberTextBox.Text <> "" Or PagerNumberTextBox.Text <> "" Or
CellPhoneNumberTextBox.Text <> "" Or VoiceMailNumberTextBox.Text <> "" Then
If ContactInfoStreamWriter IsNot Nothing Then ' Check if the file is open
Dim info As String = ""
info = String.Format("{0},{1},{2},{3},{4},{5}", _
NameTextBox.Text, PhoneNumberTextBox.Text, PagerNumberTextBox.Text,
CellPhoneNumberTextBox.Text, VoiceMailNumberTextBox.Text, EmailAddressTextBox.Text)
ContactInfoStreamWriter.WriteLine(info)
With NameTextBox
.Clear()
.Focus()
End With
PhoneNumberTextBox.Clear()
PagerNumberTextBox.Clear()
CellPhoneNumberTextBox.Clear()
VoiceMailNumberTextBox.Clear()
EmailAddressTextBox.Clear()
Else ' File is not open
MessageBox.Show("You must open the file before you can save your contact information.", "File is Not Open",
MessageBoxButtons.OK, MessageBoxIcon.Information)
' Display the File Open dialog box.
OpenToolStripMenuItem_Click(sender, e)
End If
Else
MessageBox.Show("Please enter your name and at least 1 number where you can be reached.", "Data Entry Error",
MessageBoxButtons.OK)
NameTextBox.Focus()
End If
End Sub
Heres my Streamread section on the form to lookup in combo box.
Imports System.IO
Public Class LookupForm
Private Sub LookupForm_Load(sender As Object, e As System.EventArgs) Handles Me.Load
' Load the items into the NameComboBox list.
Dim ResponseDialogResult As DialogResult
Dim LineString As String
Dim FieldString As String()
Try
' Open the file.
Dim ContactInfoStreamReader As StreamReader = New StreamReader("C:\Users\Cherokee\Documents\Cherokees Files\School Stuff\Visual Basic\Week 8 Data Files\pg465Ex11.5\pg465Ex11.5\pg465Ex11.5\bin\Debug\TextFile.txt")
' Read all the elements into the list.
Do Until ContactInfoStreamReader.Peek = -1
LineString = ContactInfoStreamReader.ReadLine()
FieldString = LineString.Split(CChar(","))
LineString = FieldString(0) 'Take First Field
NameComboBox.Items.Add(LineString)
'Set Textboxes based on position in line.
PhoneNumberTextBox.Text = FieldString(1)
PagerNumberTextBox.Text = FieldString(2)
CellPhoneNumberTextBox.Text = FieldString(3)
VoiceMailNumberTextBox.Text = FieldString(4)
EmailAddressTextBox.Text = FieldString(5)
Loop
' Close the file.
ContactInfoStreamReader.Close()
Catch ex As Exception
' File missing.
ResponseDialogResult = MessageBox.Show("Create a new file?", "File Not Found",
MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If ResponseDialogResult = Windows.Forms.DialogResult.No Then
' Exit the program.
Me.Close()
End If
End Try
End Sub

You can Split the line read and take the column position you require as for example if first column is the name then your code becomes as below:
' Open the file.
Dim ContactInfoStreamReader As StreamReader = New StreamReader("TextFile.txt")
' Read all the elements into the list.
Do Until ContactInfoStreamReader.Peek = -1
String lineRead = ContactInfoStreamReader.ReadLine()
Dim fields as String() = lineRead.Split(",")
NameString = fields(0) 'Take First Field
NameComboBox.Items.Add(NameString)
'Set Textboxes based on position in line.
'E.g. if Age is column 2 then
AgeTextBox.Text = fields(1)
Loop
' Close the file.
ContactInfoStreamReader.Close()

Related

vb.net save textbox values for later use

I use a textbox in my form to search for words in pdf files. I want to save these search words somewhere for later use. So when the user types a letter in the textbox there will be a pulldown with previous searched words. Something like windows does in Explorer.
Does anyone have an example or is someone familiar with this?
You can store and retrieve a list of search words in an application settings entry of type StringCollection as the data source of the TextBox.AutoCompleteCustomSource property.
Add new entry
Select YourAppName Properties from the Project menu.
Select the Settings tab.
Add new entry in the Name column, say: SearchWords.
From the Type column, select System.Collections.Specialized.StringCollection.
Close the dialog and save.
Retrieve the search words
In the Form's constructor or Load event, say you have a search TextBox named txtSearch:
' +
Imports System.Linq
Imports System.Collections.Specialized
Private Sub YourForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
If My.Settings.SearchWords Is Nothing Then
My.Settings.SearchWords = New StringCollection
End If
Dim acc As New AutoCompleteStringCollection
acc.AddRange(My.Settings.SearchWords.Cast(Of String).ToArray())
txtSearch.AutoCompleteMode = AutoCompleteMode.Suggest
txtSearch.AutoCompleteSource = AutoCompleteSource.CustomSource
txtSearch.AutoCompleteCustomSource = acc
End Sub
Update the collection
You need to add the new words whenever you perform a search:
' When you click a search button...
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
AddSearchWord()
End Sub
' If you call the search routine when you press the Enter key...
Private Sub txtSearch_KeyDown(sender As Object, e As KeyEventArgs) Handles txtSearch.KeyDown
If e.KeyCode = Keys.Enter Then
AddSearchWord()
End If
End Sub
' Update the collection...
Private Sub AddSearchWord()
If txtSearch.Text.Trim.Length = 0 Then Return
If Not txtSearch.AutoCompleteCustomSource.Contains(txtSearch.Text) Then
If txtSearch.AutoCompleteCustomSource.Count > 10 Then
txtSearch.AutoCompleteCustomSource.RemoveAt(
txtSearch.AutoCompleteCustomSource.Count - 1)
End If
txtSearch.AutoCompleteCustomSource.Insert(0, txtSearch.Text)
End If
End Sub
Save the collection
Update the SearchWord string collection when you close the Form:
Private Sub YourForm_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
My.Settings.SearchWords = New StringCollection
My.Settings.SearchWords.AddRange(txtSearch.AutoCompleteCustomSource.Cast(Of String).ToArray)
My.Settings.Save()
End Sub
Demo
I found some code Saving text box values to a file to load again that I changed to my needs. It saves the content of my ComboBox1 to a textfile when I click my Submit button. When I load the form the textfile is read and loaded into the ComboBox1 as previous used searches.
'now save the search word to our textfile
PresetName = TextBoxFreeText.Text
If PresetName <> "" Then
TextBoxFreeText.Items.Add(PresetName)
Call SaveData(PresetName)
End If
The code to load the saved values:
Private Sub ReadData()
If My.Computer.FileSystem.FileExists(FilePath) = True Then
myReader = New StreamReader(FilePath)
Dim myText = myReader.ReadLine
While myText IsNot Nothing
listPreset.Add(myText)
myText = myReader.ReadLine
End While
myReader.Close()
'Add Preset Names to ComboBox
If listPreset.Count > 0 Then
Dim PresetName As String
Dim index As Integer
For i = 0 To listPreset.Count - 1
index = listPreset.Item(i).IndexOf(",")
PresetName = Mid(listPreset.Item(i), 1, index)
TextBoxFreeText.Items.Add(PresetName)
Next
End If
End If
End Sub
The code to save the content of ComboBox1
Private Sub SaveData(ByVal PresetName As String)
Dim FileString As String = PresetName & ","
'Build File String
FileString &= TextBoxFreeText.Text & ","
listPreset.Add(FileString)
myWriter = New StreamWriter(FilePath)
For i = 0 To listPreset.Count - 1
myWriter.WriteLine(listPreset.Item(i))
Next
myWriter.Close()
End Sub
There are still two things I want to change. I will ask in a new question.
prevent duplicate search string to be entered in the textfile.
set a maximum to the search string loaded in ComboBox1 (maybe 10 words)

closing mdi child form causes System.ObjectDisposedException

i created a mdi database application. One child form has a datagridview. when clicking on a button on that form a new form opens with a pdfviewer(AxAcroPDF1) on it. This form shows a pdf document stored in the sql server database.
closing this form is done by Me.Close(). It closes it, but when i do it several times, opening that form and closing it, then at one point i get a
System.ObjectDisposedException which says Cannot access a disposed object and it isn't caught either in the try catch block.
It also says The application is in break mode. Your app has entered a break state, but there is no code to show because all threads where executing external code(typically system or framwork code)
Never experienced this kind of problem before.
Here is the code to launch the form with the pdf viewer
Private Sub btnShowDocument_Click(sender As Object, e As EventArgs) Handles btnShowDocument.Click
frmDocument = New frmShowDocumentatie
rowIndex = dgvData.CurrentRow.Index
FileName = dgvData.Item(6, rowIndex).Value
If FileName = "" Then
MessageBox.Show("Can't open documentation" & vbNewLine & "File doesn't exist", "Database Info", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
frmDocument.Show()
End If
End Sub
And here's the form that opens up then
Imports System.Data.SqlClient
Public Class frmShowDocumentatie
'local variables to get passed the public shared values from
'curent selected row index and document name in datagridview
Private iRow As Integer
Private fName As String
Private Sub frmShowDocumentatie_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'sets the mdi parent
MdiParent = MDIParent1
'sets the text of the form to the filename of pdf bestand
Me.Text = "Document: " & getFilename()
'loads the pdf bestand, need the filepath which is provided by getfilepath function
AxAcroPDF1.src = GetFilePath()
'gets the values from the selected row index and corrsponding filename
iRow = frmDataView.rowIndex
fName = frmDataView.FileName
tsmiDocument.Text = "Document: " & getFilename()
End Sub
'function for getting the filename of selected pdf file in datagridview
Public Function getFilename() As String
fName = frmDataView.FileName
getFilename = fName
End Function
'gets the file path of selected pdf bestand
Function GetFilePath() As String
'Dim i As Integer = frmVerledenOverzicht.dgvData.CurrentRow.Index
'Dim filename As String = frmVerledenOverzicht.dgvData.Item(6, i).Value
Dim sFilePath As String
Dim buffer As Byte()
Using conn As New SqlConnection("Server=.\SQLEXPRESS;Initial Catalog=AndriesKamminga;Integrated Security=True;Pooling=False")
conn.Open()
Using cmd As New SqlCommand("Select Bestand From dbo.PaVerledenOverzicht WHERE Documentatie =" & "'" & getFilename() & "';", conn)
buffer = cmd.ExecuteScalar()
End Using
conn.Close()
End Using
sFilePath = System.IO.Path.GetTempFileName()
System.IO.File.Move(sFilePath, System.IO.Path.ChangeExtension(sFilePath, ".pdf"))
sFilePath = System.IO.Path.ChangeExtension(sFilePath, ".pdf")
System.IO.File.WriteAllBytes(sFilePath, buffer)
'returns the file path needed for AxAcroPDF1
GetFilePath = sFilePath
End Function
Private Sub tsmiSluiten_Click(sender As Object, e As EventArgs) Handles tsmiSluiten.Click
Try
Me.Close()
Catch ex As Exception
MessageBox.Show(ex.Message, "Database Info", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
End Class
anyone knows what's causing this exception and why is the program crashing instead of being caught in the try catch block
Am using visual studio community edition 2017

Import CSV file to database using VB

I need to import the information from a CSV txt file to a database using the DataGridView in my form. The application should allow the user to open a .txt file and then update the DataGridView table in my form. I am able to get the file, but am unable to update the grid using the file. I can update textboxes, but cannot figure out how to update the grid. Can anyone help me out with this?
Imports Microsoft.VisualBasic.FileIO
Imports System.IO
Public Class Form1
Private fileToOpen As String 'the file to be opened and read
Private responseFileDialog As DialogResult 'response from OpenFileDialog
Private myStreamReader As StreamReader 'the reader object to get contents of file
Private myStreamWriter As StreamWriter 'the writer object to save contents of textbox
Private myTextFieldParser As TextFieldParser ' To parse text to searched.
Dim myDataAdapter As OleDb.OleDbDataAdapter
Dim myString() As String
Dim myRow As DataRow
Private Sub PeopleBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs) Handles PeopleBindingNavigatorSaveItem.Click
Me.Validate()
Me.PeopleBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.MyContactsDataSet)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'MyContactsDataSet.People' table. You can move, or remove it, as needed.
Me.PeopleTableAdapter.Fill(Me.MyContactsDataSet.People)
End Sub
Private Sub OpenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles OpenToolStripMenuItem.Click
Dim fileContentString As String 'contents of the file
Dim update As New OleDb.OleDbCommandBuilder(myDataAdapter)
'Dim myRow As DataRow
'set the properties of the OpenFileDialog object
OpenFileDialog1.InitialDirectory = My.Computer.FileSystem.CurrentDirectory
OpenFileDialog1.Title = "Select File to View..."
OpenFileDialog1.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"
'responseFileDialog contains holds the response of the user (which button they selected)
responseFileDialog = OpenFileDialog1.ShowDialog()
'check to see if the user select OKAY, if not they selected CANCEL so don't open anything
If (responseFileDialog <> System.Windows.Forms.DialogResult.Cancel) Then
'make sure there isn't a file already open, if there is then close it
If (myStreamReader IsNot Nothing) Then
myStreamReader.Close()
'TextBoxFileOutput.Clear()
End If
'open the file and read its text and display in the textbox
fileToOpen = OpenFileDialog1.FileName
myStreamReader = New StreamReader(OpenFileDialog1.FileName)
initTextFieldParser()
'loop through the file reading its text and adding it to the textbox on the form
Do Until myStreamReader.Peek = -1
fileContentString = myStreamReader.ReadLine()
'Try
' myTextFieldParser = New TextFieldParser(fileToOpen)
' myTextFieldParser.TextFieldType = FieldType.Delimited
' myTextFieldParser.SetDelimiters(",")
'Catch ex As Exception
' MessageBox.Show("Cannot Open File to Be Read!")
'End Try
myTextFieldParser.TextFieldType = FieldType.Delimited
myString = TextFieldParser.NewLine()
myRow.Item("FirstName") = myString(1)
MyContactsDataSet.Tables("People").Rows.Add(myRow)
PeopleTableAdapter.Update(MyContactsDataSet)
'TextBoxFileOutput.AppendText(fileContentString)
'TextBoxFileOutput.AppendText(Environment.NewLine)
Loop
'close the StreamReader now that we are done with it
myStreamReader.Close()
'SaveToolStripMenuItem.Enabled = True
End If
End Sub
Private Sub initTextFieldParser()
'Close myTextFieldParser in case the user is surfing through the records and then
'decides to search for a particular last name --> Basically start searching from beginning of the file
If (myTextFieldParser IsNot Nothing) Then
myTextFieldParser.Close()
End If
Try
myTextFieldParser = New TextFieldParser(fileToOpen)
myTextFieldParser.TextFieldType = FieldType.Delimited
myTextFieldParser.SetDelimiters(",")
Catch ex As Exception
MessageBox.Show("Cannot Open File to Be Read!")
End Try
End Sub
End Class
updating gridview with your file content
Import System.IO as we gonna need StreamReader
Using reader As New StreamReader("filepath")
DataGridView1.Columns.Add("col1",reader.ReadToEnd())
End Using
check this out!

Importing a CSV into a combobox, then changing other things in VB

What I want to do is import a CSV file (called fwlist.txt), that looks like this:
modelname,power type,pic,part number,firmware, option1, option 1, etc
End result, i would like a combobox that shows the modelname, and when the model name is selected from the pulldown, it updates various labels and text boxes on the form with other information.
Here's what I have so far:
Dim filename As String = "fwlist.txt"
Dim pwrtype As String
Dim pic As String
Dim partnum As String
Dim lineread As String
Dim FirmwareName As String
Private Sub ReadFirmwaresLoad(sender As Object, e As EventArgs) Handles Me.Load
' Load the items into the NameComboBox list.
Dim ResponseDialogResult As DialogResult
Try
Dim FirmwareStreamReader As StreamReader = New StreamReader(filename)
' Read all the elements into the list.
Do Until FirmwareStreamReader.Peek = -1
lineread = FirmwareStreamReader.ReadLine()
Dim fields As String() = lineread.Split(",")
FirmwareName = fields(0) 'Take First Field
cbFW.Items.Add(FirmwareName)
'Set Text labels based on position in line.
pwrtype = fields(1)
pic = fields(2)
partnum = fields(3)
(...etc through options)
Loop
' Close the file.
FirmwareStreamReader.Close()
Catch ex As Exception
' File missing.
ResponseDialogResult = MessageBox.Show("File not Found!", "File Not Found",
MessageBoxButtons.OK, MessageBoxIcon.Question)
If ResponseDialogResult = DialogResult.OK Then
' Exit the program.
Me.Close()
End If
End Try
End Sub
Private Sub cbFW_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbFW.SelectedIndexChanged
lblPwrType.Text = pwrtype
lblPic.Text = pic
lblPartNum.Text = parnum
....etc thruogh options
End Sub
This code works, but only sort of. If i select anything from the combo box, it only gives me the information from the very last line of the CSV file - even if its the first entry in the box. I'm pretty sure it's something simple that I'm messing up.. anyone help?
First we read the lines into Firmware objects then we set this List(Of Firmware) as the DataSource of the ComboBox.
Then we handle the SelectedIndexChanged event of the ComboBox which will get the currently selected firmware and loads its data to the TextBox controls.
This is a tested, working example below:
Public Class Firmware
Public Property ModelName As String
Public Property PowerType As String
Public Property Pic As String
Public Property PartNumber As String
Public Property Firmware As String
Public Property Option1 As String
End Class
Public Class MainForm
Private Sub btnLoad_Click(sender As Object, e As EventArgs) Handles btnLoad.Click
Dim lines As String() = Nothing
Try
' Read the file in one step
lines = File.ReadAllLines("fwlist.txt")
Catch ex As Exception
Dim dialogResult As DialogResult = MessageBox.Show(Me, "File not found! Would you like to exit program?", "Error reading file", MessageBoxButtons.YesNo, MessageBoxIcon.Error, MessageBoxDefaultButton.Button2)
If dialogResult = DialogResult.Yes Then
Me.Close()
End If
Exit Sub
End Try
Dim firmwares As List(Of Firmware) = New List(Of Firmware)
For Each line As String In lines
Dim rawData As String() = line.Split({","}, StringSplitOptions.None)
' Create Firmware object from each line
Dim firmware As Firmware = New Firmware() With
{
.ModelName = rawData(0),
.PowerType = rawData(1),
.Pic = rawData(2),
.PartNumber = rawData(3),
.Firmware = rawData(4),
.Option1 = rawData(5)
}
' We store the read firmwares into a list
firmwares.Add(firmware)
Next
' Set the list as the data source of the combobox
' DisplayMember indicates which property will be shown in the combobox
With cboModelNames
.DataSource = firmwares
.DisplayMember = "ModelName"
End With
End Sub
Private Sub cboModelNames_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboModelNames.SelectedIndexChanged
RefreshForm()
End Sub
Private Sub RefreshForm()
' Get the selected item as Firmware object
Dim currentFirmware As Firmware = DirectCast(cboModelNames.SelectedItem, Firmware)
' Refresh all the textboxes with the information
With currentFirmware
txtPowerType.Text = .PowerType
txtPic.Text = .Pic
txtPartNumber.Text = .PartNumber
txtFirmware.Text = .Firmware
txtOption1.Text = .Option1
End With
End Sub
End Class
Every time you set the value of a variable like pwrtype, its old value is thrown away and there is no way to get it back. And even if you did save multiple values for each variable, you would need a way to figure out which value goes with the currently selected item in the combo box. To resolve these two issues you need:
a way to group values from the same line together
a way to save all values read from the file, not just the most recent ones
Let's start with the first issue, grouping values together. In the example code below, I created a Structure type called FirmwareInfo to serve that purpose. Each FirmwareInfo has its own pwrtype, pic, etc.
The other piece of the puzzle that you are missing is a way to save more than one Firmware. The easiest way to do this is to add each FirmwareInfo to the combo box's item list, instead of adding just the display string. The combo box will convert each item to a string in the UI; the ToString() method tells it how you want this conversion to be done.
I haven't run this example code so I can't guarantee there aren't mistakes in there, but hopefully it's enough to show the general idea.
Dim filename As String = "fwlist.txt"
Structure FirmwareInfo
Public pwrtype As String
Public pic As String
Public partnum As String
Public FirmwareName As String
Public Overrides Function ToString() As String
Return FirmwareName
End Function
End Structure
Private Sub ReadFirmwaresLoad(sender As Object, e As EventArgs) Handles Me.Load
' Load the items into the NameComboBox list.
Dim ResponseDialogResult As DialogResult
Try
Dim FirmwareStreamReader As StreamReader = New StreamReader(filename)
' Read all the elements into the list.
Do Until FirmwareStreamReader.Peek = -1
Dim lineread = FirmwareStreamReader.ReadLine()
Dim fields As String() = lineread.Split(",")
Dim info As New FirmwareInfo With {
.FirmwareName = fields(0),
.pwrtype = fields(1),
.pic = fields(2),
.partnum = fields(3)
}
cbFW.Items.Add(info)
Loop
' Close the file.
FirmwareStreamReader.Close()
Catch ex As Exception
' File missing.
ResponseDialogResult = MessageBox.Show("File not Found!", "File Not Found",
MessageBoxButtons.OK, MessageBoxIcon.Question)
If ResponseDialogResult = DialogResult.OK Then
' Exit the program.
Me.Close()
End If
End Try
End Sub
Private Sub cbFW_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbFW.SelectedIndexChanged
Dim currentInfo = DirectCast(cbFW.SelectedItem, FirmwareInfo)
lblPwrType.Text = currentInfo.pwrtype
lblPic.Text = currentInfo.pic
lblPartNum.Text = currentInfo.parnum
' ....etc through options
End Sub

how to make comma-delimited txt file using streamwriter

It is writing to txt file file but only 1 field per line. I need a comma between each field in the text file so each record is on 1 line. How do I do that?
Here's this portion of my code.
Imports System.IO
Public Class ContactInfoForm
' Declare module-level variable.
Private ContactInfoStreamWriter As StreamWriter
Private Sub SaveButton_Click(sender As System.Object, e As System.EventArgs) Handles SaveButton.Click
' Save the users contact information to the end of the file.
' Make sure name field and at least 1 number field is not empty.
If NameTextBox.Text <> "" And PhoneNumberTextBox.Text <> "" Or PagerNumberTextBox.Text <> "" Or
CellPhoneNumberTextBox.Text <> "" Or VoiceMailNumberTextBox.Text <> "" Then
If ContactInfoStreamWriter IsNot Nothing Then ' Check if the file is open
ContactInfoStreamWriter.WriteLine(NameTextBox.Text)
ContactInfoStreamWriter.WriteLine(PhoneNumberTextBox.Text)
ContactInfoStreamWriter.WriteLine(PagerNumberTextBox.Text)
ContactInfoStreamWriter.WriteLine(CellPhoneNumberTextBox.Text)
ContactInfoStreamWriter.WriteLine(VoiceMailNumberTextBox.Text)
ContactInfoStreamWriter.WriteLine(EmailAddressTextBox.Text)
With NameTextBox
.Clear()
.Focus()
End With
PhoneNumberTextBox.Clear()
PagerNumberTextBox.Clear()
CellPhoneNumberTextBox.Clear()
VoiceMailNumberTextBox.Clear()
EmailAddressTextBox.Clear()
Else ' File is not open
MessageBox.Show("You must open the file before you can save your contact information.", "File is Not Open",
MessageBoxButtons.OK, MessageBoxIcon.Information)
' Display the File Open dialog box.
OpenToolStripMenuItem_Click(sender, e)
End If
Else
MessageBox.Show("Please enter your name and at least 1 number where you can be reached.", "Data Entry Error",
MessageBoxButtons.OK)
NameTextBox.Focus()
End If
End Sub
It is because you're using WriteLine where it writes its parameter into a single line. You can either use .Write() or use String.Format(), example:
Dim info As String = ""
info = String.Format("{0},{1},{2},{3},{4},{5}", _
NameTextBox.Text, PhoneNumberTextBox.Text, PagerNumberTextBox.Text, CellPhoneNumberTextBox.Text, VoiceMailNumberTextBox.Text, EmailAddressTextBox.Text)
ContactInfoStreamWriter.WriteLine(info)