how to make comma-delimited txt file using streamwriter - vb.net

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)

Related

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

Allowing multiple files to be processed through one module

I've created a program to modify security settings of a .pdf file.
This works fine for one file - but I want to allow editing multiple .pdf's with the touch of one button and am struggling to make it work.
I have pasted the code for my GUI below, "Modify_PDF" is the module that runs the pdf security modification code. Is it possible to run multiple files through this module from here?
Dim source_file As String = ""
''' Handles clicking of the 'Open file' button
Private Sub open_button_Click(sender As System.Object, e As System.EventArgs) Handles open_button.Click
Dim input As FileStream = Nothing
'Set filter to only allow compatible files
OpenFileDialog.Filter = "PDF documents (*.pdf)|*.pdf"
'Allow multiple files to be opened
OpenFileDialog.Multiselect = True
'open the file selection dialogue
If OpenFileDialog.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Try
input = OpenFileDialog.OpenFile()
Catch Ex As Exception
MsgBox("Error opening file: " & vbCrLf & Ex.Message)
Finally
'Check this again to ensure no exception on open.
If (input IsNot Nothing) Then
input.Close()
End If
End Try
If input IsNot Nothing Then
source_file = OpenFileDialog.FileName
If Modify_PDF.process_file(source_file, "") Then
PDF_name.Text = Path.GetFileName(OpenFileDialog.FileName)
input.Close()
modify_button.Enabled = Modify_PDF.process_file(source_file, "") 'Allow report to be created if processing succeeds
End If
End If
End If
End Sub
''' Handles clicking of the 'Modify PDF' button
Private Sub generate_button_Click(sender As System.Object, e As System.EventArgs) Handles modify_button.Click
Modify_PDF.modify_pdf(source_file, source_file, "")
End Sub
Try it like this:
If OpenFileDialog.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Try
For Each FileName as String in OpenFileDialog.FileNames
'Do something with the filename here
Next
Catch ...

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

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

upload multiple files to a local folder in vb.net

I am trying to create a function that will allow user to upload multiple files to a local folder.
currently i am able to upload just one file. i needed to upload more files in one go.
what i use for opening files/folder
a.Multiselect = True
If a.ShowDialog() = Windows.Forms.DialogResult.OK Then
removeatt.Show()
removeatt.Text = "Remove Attachment"
fpath.Text = a.FileName
address.Text = System.IO.Path.GetFileName(a.FileName)
Dim file As String
file = fpath.Text.ToString
Label7.Text = file
If fpath.Text = "-" Then
removeatt.Hide()
Else
removeatt.Show()
End If
End If
what i use for saving attachment
If fpath.Text = "-" Then
Else
My.Computer.FileSystem.CopyFile(fpath.Text = "-", dir2 + Upload.Label16.Text, Microsoft.VisualBasic.FileIO.UIOption.AllDialogs, Microsoft.VisualBasic.FileIO.UICancelOption.DoNothing)
End If
any help is appreciated
thanks
It is not entirely clear to me where you handle the selected files, the first one is about removing attachments and the saving-part is not about uploading, it saves a file to the disk of the user as it seems.
Generally i'd recommend you to write a function that handles one file at a time so you can feed the function with the list of files to be copied in a for each-loop. The function is a bit "basic" to demonstrate what i mean.
Public Function CopyToDisk(ByVal DestinationPath As String, ByVal Sourcepath As String) As String
If Not System.IO.File.Exists(Sourcepath) Then
Return "Source missing" & Sourcepath
End If
Try
File.Copy(Sourcepath, DestinationPath)
Catch ex As Exception
Return ex.Message
End Try
Return "ok"
End Function
Well, have a look at the example from MSDN here, it has a filepicker and then it puts the objects in an array you can loop through and copy it where you want it to copy.
Here is the MSDN-original
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
InitializeOpenFileDialog()
End Sub
Private Sub Selectfilebutton_Click_1(sender As Object, e As EventArgs) Handles Selectfilebutton.Click
Dim dr As DialogResult = Me.OpenFileDialog1.ShowDialog()
If (dr = System.Windows.Forms.DialogResult.OK) Then
' Read the files
Dim file As String
For Each file In OpenFileDialog1.FileNames
'' you can loop through the array of objects and use a function to do the copying
' so for instance with my function it would be :
' copytodisk(Destination, file.filename)
' Create a PictureBox for each file, and add that file to the FlowLayoutPanel.
Try
Dim pb As New PictureBox()
Dim loadedImage As Image = Image.FromFile(file)
pb.Height = loadedImage.Height
pb.Width = loadedImage.Width
pb.Image = loadedImage
FlowLayoutPanel1.Controls.Add(pb)
Catch SecEx As SecurityException
' The user lacks appropriate permissions to read files, discover paths, etc.
MessageBox.Show("Security error. Please contact your administrator for details.\n\n" & _
"Error message: " & SecEx.Message & "\n\n" & _
"Details (send to Support):\n\n" & SecEx.StackTrace)
Catch ex As Exception
' Could not load the image - probably permissions-related.
MessageBox.Show(("Cannot display the image: " & file.Substring(file.LastIndexOf("\"c)) & _
". You may not have permission to read the file, or " + "it may be corrupt." _
& ControlChars.Lf & ControlChars.Lf & "Reported error: " & ex.Message))
End Try
Next file
End If
End Sub
Public Sub InitializeOpenFileDialog()
' Set the file dialog to filter for graphics files.
Me.OpenFileDialog1.Filter = _
"Images (*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|" + _
"All files (*.*)|*.*"
' Allow the user to select multiple images.
Me.OpenFileDialog1.Multiselect = True
Me.OpenFileDialog1.Title = "My Image Browser"
End Sub

Change date format in code only

I've a code that simply creates a folder in a directory and gives it a name based on the values of a datetimepicker and a text box.
The date picker is displayed on the form as "16 October 2013" (how I want to keep it) but when I generate the file name I would lime the date to read in the format "161013"
The code I'm using is below if that helps
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim lMailbox As String
lMailbox = t2.Text & "-" & d1.Text
' Check if folder exists, if not: create it
If Not Directory.Exists(nMailbox & lMailbox) Then
Directory.CreateDirectory(nMailbox & lMailbox)
' Folder created message
MessageBox.Show("Mailbox created!", "Lynx Control Panel", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
' Folder already exists
MessageBox.Show("Mailbox already exists!", "Lynx Control Panel", MessageBoxButtons.OK, MessageBoxIcon.Stop)
End If
End Sub
The nMailbox & lMailbox are declared at the top of the code page
d1 is the name of the datepicker
I'm very new to VB.net and would appreciate any help
Thanks
try this:
lMailbox = t2.Text & "-" & d1.Value.ToString("ddMMyy")
The format options are the same as for DateTime string formatting. Use Value of the DTP rather than the Text which is formatted otherwise/