Import CSV file to database using VB - vb.net

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!

Related

Print-to-screen log window

I have to run a process - through the execution of a batch script - which produces an output that is saved as a text file. Furthermore, I need to see this output on a form of the application of mine and, to do this, I've set an iterative timer which updates every second the content of a non-editable RichTextBox but I have two issues:
Each time the timer stops and restarts, I need to create a copy the output file, since the file is used from another process and can't be loaded onto the software as it is;
Creating and loading this text file may be honerous in terms of hardware capability, since this file may reach really big size (even more than 5 GB).
Here is the code I'm providing:
Private Sub Form9_Load(sender As Object, e As EventArgs) Handles MyBase.Load
[...]
Me.Timer1.Interval = TimeSpan.FromSeconds(1).TotalMilliseconds
Me.Timer1.Start()
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Application.DoEvents()
Dim p = Process.GetProcessesByName("fds2ftmi_win_64")
Dim appPath As String = Path.GetDirectoryName(Application.ExecutablePath)
If My.Computer.FileSystem.FileExists(Form1.TextBox5.Text + "/HTAoutput.dat") Then
If p.Count > 0 Then
RichTextBox1.Refresh()
My.Computer.FileSystem.CopyFile(Form1.TextBox5.Text + "/HTAoutput.dat", Form1.TextBox5.Text + "/HTAoutemp.dat", Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs, FileIO.UICancelOption.DoNothing)
RichTextBox1.LoadFile(Form1.TextBox5.Text + "/HTAoutemp.dat", RichTextBoxStreamType.PlainText)
RichTextBox1.SelectionStart = RichTextBox1.TextLength
RichTextBox1.ScrollToCaret()
Else
Call Button3_Click(sender, e)
End If
End If
End Sub
Is there a more efficient way to show this stream-writing onto my log-window?
Thanks all are gonna answer me
EDIT 1:
Here is the code I'm providing:
Dim p = Process.GetProcessesByName("fds2ftmi_win_64")
Dim appPath As String = Path.GetDirectoryName(Application.ExecutablePath)
Dim str As FileStream
str = File.Open(Form1.TextBox5.Text + "/HTAoutput.dat", FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
If My.Computer.FileSystem.FileExists(Form1.TextBox5.Text + "/HTAoutput.dat") Then
If p.Count > 0 Then
RichTextBox1.LoadFile(str, RichTextBoxStreamType.PlainText)
RichTextBox1.SelectionStart = RichTextBox1.TextLength
RichTextBox1.ScrollToCaret()
Application.DoEvents()
Else
Call Button3_Click(sender, e)
End If
End If
Here is a simple demonstration of opening a file once and continuing to read only new data as it is added to that file.
Create a new WinForms Application project with two forms. Add a TextBox and a Button to each form. Make the TextBox multiline on Form1. Add a text file to your project named Test.txt and set Copy to Output Directory to Copy always. Add some default text to the file. Add this code to Form1:
Imports System.IO
Public Class Form1
Private reader As StreamReader
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Open the file for reading and allow sharing.
Dim filePath = Path.Combine(Application.StartupPath, "Test.txt")
Dim strm = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
reader = New StreamReader(strm)
'Read all available text and append to the existing text.
TextBox1.Text = reader.ReadToEnd()
Form2.Show()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'Read all available text and append to the existing text.
TextBox1.AppendText(reader.ReadToEnd())
End Sub
End Class
and add this code to Form2:
Imports System.IO
Public Class Form2
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim filePath = Path.Combine(Application.StartupPath, "Test.txt")
'Write a new line of text to the file.
File.AppendAllText(filePath, Environment.NewLine & TextBox1.Text)
'Get ready for the next line of text.
TextBox1.Clear()
TextBox1.Select()
End Sub
End Class
Run the project and you'll see your default text in Form1. Enter some text into Form2 and click the Button. Do that a few times. Now click the Button on Form1. Voila! Repeat that cycle and see the text you enter on one form magically appear on the other.
Now go back and examine the code more closely. You can see that Form2 appends a line of code to the file each time you click the Button. Form1 reads the initial contents of the file when it loads and displays that, but it keeps the file open. Each time you click the Button, it will read only the new data, i.e. only the data after where it previously read up to. It then appends that new text to the existing text in the TextBox.

Reference Form2.DataGridView from code on Form1

I am new to this forum. This is my first post, though I have spent a lot of time here searching for answers.
I have used VBA in Excel for many years, but have recently started using VB in Visual Studio 2015. I have created Form 1 as a MDIContainer and have another form opened inside this. This form (FormXYZ) contains a DataGridView.
Form1 has a MenuStrip and a I am currently trying to write the code, when one of these menu items is selected, to populate the DGV from a CSV. At this stage I am only trying to read the data and then I will work on the code to split the strings up.
Screenshot
I have no problem with selecting a file to import and the streamreader appears to read the file, but no data makes it to the DGV.
When I tried putting the code on FormXYZ for a button click event, the DGV was populated. So I believe the error is due to the way I am referencing the DGV, as the code for the MenuStrip_Click event is on Form1, but the DGV is on FormXYZ.
I would appreciate if somebody could point out where I am going wrong. My code is shown below.
Thanks Tepede
Imports System.IO
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim FormXYZ As New FormXYZ()
FormXYZ.MdiParent = Me 'Set the Parent Form of the Child window.
FormXYZ.Show() 'Display the XYZ form.
End Sub
'-------------------------------------
'StripMenu click command to import CSV
Public Sub TSMIFileImportCSV_Click(sender As Object, e As EventArgs) Handles TSMIFileImportCSV.Click
Dim Filename As String
Dim RowValue As String
Dim OpenFile As OpenFileDialog = New OpenFileDialog()
'Open file dialog
With OpenFile
.Filter = "CSV (*.CSV)|*.csv"
.FilterIndex = 1
.InitialDirectory = "C:\"
.Title = "Open File"
.CheckFileExists = False
End With
If OpenFile.ShowDialog() = DialogResult.OK Then
Filename = OpenFile.FileName
End If
'---------
' Read CSV file content
Dim objReader As StreamReader = New StreamReader(Filename)
While objReader.Peek() <> -1
RowValue = objReader.ReadLine()
'Fist column is Boolean, the second should have the data from the CSV file
FormXYZ.DataGridView1.Rows.Add(True, RowValue, "Test", "Test")
End While
objReader.Close()
End Sub
It looks like you are losing your instance to the FormXYZ that you displayed due to it's definition being in the Form Load. Expand the scope of that variable to be at the class level.
Public Class Form1
Private FormXYZ As FormXYZ
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
FormXYZ = New FormXYZ()
FormXYZ.MdiParent = Me 'Set the Parent Form of the Child window.
FormXYZ.Show() 'Display the XYZ form.
End Sub

Webclient.DownloadFile to Folderbrowser.Selectedpath

I want my code to download a file from a website and save it to an directory that the user has selected in the FolderBrowserDialog ... i've tried this code below without success:
' Download the files
If My.Computer.Network.IsAvailable Then
Try
wClient.DownloadFile(New Uri("DOWNLOAD LINK"), FolderBrowserDialog1.SelectedPath & "FILENAME.123")
wClient.DownloadFile(New Uri("DOWNLOAD LINK"), FolderBrowserDialog1.SelectedPath & "FileName.123)
wClient.DownloadFile(New Uri("Download LINK"), FolderBrowserDialog1.SelectedPath & "FileName.123")
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Here is some sample code I have written for you that should get you started.
first we declare wClient as a WebClient with Events so we can trigger what happens when the file downloads.I have used VLC Media Player as an example download, change to suit your needs. NOTE I did this with a button click event which you don't necessary need to do.
Imports System.ComponentModel
Imports System.Net
Public Class Form1
Private WithEvents wClient As New WebClient()
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim FolderBrowserDiaglog1 As New FolderBrowserDialog()
Dim folderPath As String = ""
Dim fileName As String = "vlc.exe"
Dim downloadFile As String = "https://get.videolan.org/vlc/2.2.6/win32/vlc-2.2.6-win32.exe" ''VLC MEDIA PLAYER
If FolderBrowserDiaglog1.ShowDialog() = DialogResult.OK Then
folderPath = FolderBrowserDiaglog1.SelectedPath
End If
If My.Computer.Network.IsAvailable Then
Dim combinePath As String = System.IO.Path.Combine(folderPath, fileName)
wClient.DownloadFileAsync(New Uri(downloadFile), combinePath)
End If
End Sub
Private Sub wClient_DownloadFileCompleted(sender As Object, e As AsyncCompletedEventArgs) Handles wClient.DownloadFileCompleted
MessageBox.Show("File Downloaded")
End Sub
End Class
Have a look in the wClient's event list and see the many options that are avalible such as the one that i have made that shows a messagebox once the file has been downloaded.
Webclient events https://msdn.microsoft.com/en-us/library/system.net.webclient_events(v=vs.110).aspx

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

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