Importing a CSV into a combobox, then changing other things in VB - vb.net

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

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)

VB.Net populating text boxes from text file

I'm creating an inventory management system where the data is stored in a text file. I'm able to save data to the text file, however on the tracker screen it should show current inventory such as: Manufacturer, Processor, Video, Form, RAM, etc. However, all my text boxes remain blank and I'm not sure why. It's not reading properly or updating the text.
frmTracker.vb
Private Sub txtManufacturer_TextChanged(sender As Object, e As EventArgs) Handles txtManufacturer.TextChanged
Dim objMyStreamReader = System.IO.File.OpenText("inventory.txt")
Dim strInventory = objMyStreamReader.ReadLine()
objMyStreamReader.Close()
txtManufacturer.AppendText(strInventory)
End Sub
This is how I'm currently saving the data to the text file.
frmItemEntry.vb
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim objMyStreamReader As System.IO.StreamReader
Dim objMyStreamWriter As System.IO.StreamWriter = System.IO.File.CreateText("inventory.txt")
Dim strInventory As String
objMyStreamWriter.WriteLine(txtManufacturerEntry.Text)
objMyStreamWriter.WriteLine(txtProcessorEntry.Text)
objMyStreamWriter.WriteLine(txtVideoEntry.Text)
objMyStreamWriter.WriteLine(txtFormEntry.Text)
objMyStreamWriter.WriteLine(txtRamEntry.Text)
objMyStreamWriter.WriteLine(txtVramEntry.Text)
objMyStreamWriter.WriteLine(txtHdEntry.Text)
objMyStreamWriter.WriteLine(chkWirelessEntry.CheckState)
objMyStreamWriter.Close()
Me.Close()
End Sub
Example from inventory.txt
Dell
i5
Nvidia
Desktop
8
4
600
0
To be honest, controls should never be used as the primary store for your data in a program. You should really be creating a class and a list of that class to store your data.
You can then read your data into the list from your file, and then, display it from there in your form.
There are several ways of navigating through the data and saving updates. The suggestion below uses buttons for next item and previous item, and a button to save update the file.
It's all pretty self explanatory, but if there's something your not sure about, please have a google and learn something new :-D
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ReadDataFile()
DisplayItem(0)
End Sub
Private Class InventoryItem
Public Property Manufacturer As String
Public Property Processor As String
Public Property Video As String
Public Property FormFactor As String
Public Property Ram As String
Public Property VRam As String
Public Property Hd As String
Public Property Wireless As CheckState
Public Sub New()
Manufacturer = ""
Processor = ""
Video = ""
FormFactor = ""
Ram = ""
VRam = ""
Hd = ""
Wireless = CheckState.Unchecked
End Sub
End Class
Dim Inventory As New List(Of InventoryItem)
Dim currentItemIndex As Integer
Private Sub ReadDataFile()
Using objMyStreamReader As New StreamReader("k:\inventory.txt")
Do Until objMyStreamReader.EndOfStream
Dim newItem As New InventoryItem
newItem.Manufacturer = objMyStreamReader.ReadLine()
newItem.Processor = objMyStreamReader.ReadLine()
newItem.Video = objMyStreamReader.ReadLine()
newItem.FormFactor = objMyStreamReader.ReadLine()
newItem.Ram = objMyStreamReader.ReadLine()
newItem.VRam = objMyStreamReader.ReadLine()
newItem.Hd = objMyStreamReader.ReadLine()
Dim wirelessValue As String = objMyStreamReader.ReadLine()
If wirelessValue = "0" Then
newItem.Wireless = CheckState.Unchecked
ElseIf wirelessValue = "1" Then
newItem.Wireless = CheckState.Checked
End If
Inventory.Add(newItem)
Loop
End Using
End Sub
Private Sub SaveDataFile()
Using objMyStreamWriter As New System.IO.StreamWriter("k:\inventory.txt", False)
For Each item As InventoryItem In Inventory
objMyStreamWriter.WriteLine(item.Manufacturer)
objMyStreamWriter.WriteLine(item.Processor)
objMyStreamWriter.WriteLine(item.Video)
objMyStreamWriter.WriteLine(item.FormFactor)
objMyStreamWriter.WriteLine(item.Ram)
objMyStreamWriter.WriteLine(item.VRam)
objMyStreamWriter.WriteLine(item.Hd)
If item.Wireless = CheckState.Checked Then
objMyStreamWriter.WriteLine("1")
Else
objMyStreamWriter.WriteLine(0)
End If
Next
End Using
End Sub
Private Sub DisplayItem(index As Integer)
With Inventory(index)
txtManufacturerEntry.Text = .Manufacturer
txtProcessorEntry.Text = .Processor
txtVideoEntry.Text = .Video
txtFormEntry.Text = .FormFactor
txtRamEntry.Text = .Ram
txtVramEntry.Text = .VRam
txtHdEntry.Text = .Hd
chkWirelessEntry.CheckState = .Wireless
End With
End Sub
Private Sub BtnUpdateItem_Click(sender As Object, e As EventArgs) Handles BtnUpdateItem.Click
With Inventory(currentItemIndex)
.Manufacturer = txtManufacturerEntry.Text
.Processor = txtProcessorEntry.Text
.Video = txtVideoEntry.Text
.FormFactor = txtFormEntry.Text
.Ram = txtRamEntry.Text
.VRam = txtVramEntry.Text
.Hd = txtHdEntry.Text
.Wireless = chkWirelessEntry.CheckState
End With
SaveDataFile()
End Sub
Private Sub BtnPreviousItem_Click(sender As Object, e As EventArgs) Handles BtnPreviousItem.Click
If currentItemIndex > 0 Then
currentItemIndex -= 1
DisplayItem(currentItemIndex)
End If
End Sub
Private Sub BtnNextItem_Click(sender As Object, e As EventArgs) Handles BtnNextItem.Click
If currentItemIndex < Inventory.Count - 1 Then
currentItemIndex -= 1
DisplayItem(currentItemIndex)
End If
End Sub
First change the format of your text file.
Dell,i5,Nvidia,Desktop,8,2,600,True
Acer,i7,Intel,Desktop,16,4,1GB,True
HP,Pentium,Diamond Viper,Desktop,4,2,200,False
Surface Pro,i7,Intel,Laptop,8,2,500,True
Each line is a record and each field in the record is separated by a comma (no spaces so we don't have to .Trim in code) (a space within a field is fine, notice Surface Pro).
Now it is easier to read the file in code.
This solution uses a BindingSource and DataBindings. This simplifies Navigation and editing and saving the data.
Public Class Form5
Private bs As BindingSource
Private dt As New DataTable
#Region "Set Up the Form"
Private Sub Form5_Load(sender As Object, e As EventArgs) Handles MyBase.Load
AddColumnsToDataTable()
FillDataTable()
AddDataBindings()
End Sub
Private Sub AddColumnsToDataTable()
'Prepare the DataTable to hold data
dt.Columns.Add("Manufacturer", GetType(String))
dt.Columns.Add("Processor", GetType(String))
dt.Columns.Add("Video", GetType(String))
dt.Columns.Add("Form", GetType(String))
dt.Columns.Add("RAM", GetType(String))
dt.Columns.Add("VRAM", GetType(String))
dt.Columns.Add("HD", GetType(String))
dt.Columns.Add("Wireless", GetType(Boolean))
End Sub
Private Sub FillDataTable()
'ReadAllLines returns an array of the lines in a text file
'inventory.txt is stored in the bin\Debug folder of your project
'This is the current directory so it does not require a full path.
Dim lines = File.ReadAllLines("inventory.txt")
'Now it is easy to split each line into fields by using the comma
For Each line As String In lines
'Split returns an array of strings with the value of each field
Dim items = line.Split(","c)
'Each item in the array can be added as a field to the DataTable row
dt.Rows.Add(items(0), items(1), items(2), items(3), items(4), items(5), items(6), CBool(items(7)))
'Notice that the last element is changed from a string to a boolean. This is
'the Wireless field which is bound to the check box. The string "True" or "False" is
'changed to a Boolean so it can be used as the .Checked property (see bindings)
Next
End Sub
Private Sub AddDataBindings()
'Create a new instance of the BindingSource class
bs = New BindingSource()
'Set the DataSource to the DataTable we just filled
bs.DataSource = dt
'Now you can set the bindings of each control
'The .Add method takes (Name of Property to Bind, the BindingSource to use, The Field name
'from the DataTable.
txtForm.DataBindings.Add("Text", bs, "Form")
txtHd.DataBindings.Add("Text", bs, "HD")
txtManufacturer.DataBindings.Add("Text", bs, "Manufacturer")
txtProcessor.DataBindings.Add("Text", bs, "Processor")
txtRam.DataBindings.Add("Text", bs, "RAM")
txtVideo.DataBindings.Add("Text", bs, "Video")
txtVram.DataBindings.Add("Text", bs, "VRAM")
'Notice on the CheckBox we are using the Checked property.
chkWireless.DataBindings.Add("Checked", bs, "Wireless")
End Sub
#End Region
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
'Add a blank row to the DataTable
'A Boolean is like a number, a String can be Nothing but a Boolean must
'have a value so we pass in False.
dt.Rows.Add(Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, False)
'Find the position of the last row
Dim i As Integer = bs.Count - 1
'Move to the new empty row
bs.Position = i
End Sub
#Region "Navigation Code"
Private Sub btnPrevious_Click(sender As Object, e As EventArgs) Handles btnPrevious.Click
'The binding source Position determins where in the data you are
'It starts at zero
If bs.Position = 0 Then
MessageBox.Show("This is the first item.")
Return 'This exits the sub, you can use Exit Sub in vb
'but Return is common in other languages so it is good to learn
Else
'As the position of the BindingSource changes the boud TextBoxes
'change their data.
bs.Position = bs.Position - 1
End If
End Sub
Private Sub btnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click
' If you are not at the end of the list, move to the next item
' in the BindingSource.
If bs.Position + 1 < bs.Count Then
bs.MoveNext()
' Otherwise, move back to the first item.
Else
bs.MoveFirst()
End If
End Sub
#End Region
#Region "Save the Data"
Private Sub SaveDataTable()
'Resave the whole file if this was a real app you would use a database
Dim sb As New StringBuilder
'A string builder keeps the code from creating lots of new strings
'Strings are immutable (can't be changed) so every time you think you are
'changing a string, you are actually creating a new one.
'The string builder is mutable (changable)
For Each row As DataRow In dt.Rows
'The ItemsArray returns an array of objects containing all the
'values in each column of the data table.
Dim rowValues = row.ItemArray
'This is a bit of Linq magic that turns the values (objects) into strings
'Underneath it is performing a For loop on each object in the array
Dim strRowValues = From o In rowValues
Select Convert.ToString(o)
'Now that we have strings we can use the String.Join with the comma
'to get the format of the text file
sb.AppendLine(String.Join(",", strRowValues))
Next
'Finally we change the StringBuilder to a real String
'The inventory.txt is stored in the bin\Debug directory so it is current directory
'no additional path required
File.WriteAllText("inventory.txt", sb.ToString)
End Sub
Private Sub Form5_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
'Because our binding is two-way any additions or changes to the text
'in the text boxes or check box are reflected in the DataTable.
SaveDataTable()
End Sub
#End Region
End Class
Once you remove the comments, there is really very little code here. The #Region...#End Region tags make it easy to collapse code sections you are not working on and find areas quickly.

Read in values from comma delimited text file and add,create object of the class, then add objects to collection

I currently have the following code:
Public Class CPUForm
Dim myCPUList As New List(Of CPUClass)
Dim Counter As Integer = 0
Private Sub CPUForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
OpenFileDialog.ShowDialog()
Try
If IO.File.Exists(OpenFileDialog.FileName) = False Then
End If
Catch ex As IO.FileNotFoundException
MessageBox.Show("The File Could Not Be Found", "Alert")
End Try
If IO.File.Exists(OpenFileDialog.FileName) = True Then
Dim sr As IO.StreamReader = IO.File.OpenText(OpenFileDialog.FileName)
Dim line As Object
Dim data() As Object
Do Until sr.EndOfStream
line = sr.ReadLine
data = line.Split(",")
Dim ACpu As New CPUClass(data(0), data(1), data(2), data(3), data(4), data(5))
myCPUList(Counter) = ACpu
Counter += 1
Loop
sr.Close()
End If
lstOut.DataSource = Nothing
lstOut.DataSource = myCPUList
End Sub
End Class
The goal here is to read-in values from a comma separated text file, create objects of the class, add those objects to the collection, and then display the collection in a listbox using an overridden ToString method.
Right now I get no errors, even at runtime. The problem is that one the file is selected, nothing happens. Nothing is displayed in the listbox as if nothing was added to the collection. Also, an overloaded constructor exists to receive the values being read in.
Turns out the code is fine, the problem was an out of place comma in the text file.

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

How to work out if a file has been read in order to read the next file?

Here is my code:
Private Sub btnDisplayOrderDetails_Click(ByVal sender As Object, _
ByVal e As EventArgs) _
Handles btnDisplayOrder Details.Click
Dim myStreamReader As StreamReader
Try
myStreamReader = File.OpenText("Textfile1.txt")
Me.txtOrderDetails.Text = myStreamReader.ReadToEnd()
Catch exc As Exception
Finally
If Not myStreamReader Is Nothing Then
myStreamReader.Close()
End If
End Try
If txtOrderDetails.Text = "" Then
Dim mystreamreader1 As StreamReader
Try
mystreamreader1 = File.OpenText("textfile2.txt")
Me.txtOrderDetails.Text = myStreamReader.ReadToEnd()
Catch ex As Exception
Finally
If Not myStreamReader Is Nothing Then
mystreamreader1.Close()
End If
End Try
End If
End Sub
What I would like this code to do is:
Read the first Text file upon button click, then when I've cleared the text Box (with the use of a different button which is already coded) I would then like to read in the second text file upon button click into the same Text box as before.
It's not clear what you are trying to do with the files. Combine them all into a single text box, or does each file belong to a specific textbox.
The looping method to place all the files into a single text box:
Dim filePath As String = "C:\Users\Practice\Practice\bin\Debug"
Dim sb As New StringBuilder
For Each f As String In Directory.GetFiles(filePath, "*.txt")
sb.AppendLine(File.ReadAllText(f))
Next
txtOrderDetails.Text = sb.ToString()
Or if it's not a list, then you go through your files one by one:
Dim test1 As String = Path.Combine(filePath, "Textbox1.txt")
If File.Exists(test1) Then
TextBox1.Text = File.ReadAllText(test1)
End If
Dim test2 As String = Path.Combine(filePath, "Textbox2.txt")
If File.Exists(test2) Then
TextBox2.Text = File.ReadAllText(test2)
End If