I am attempting to load a text file that contains a list of names into a text box using a button on the form. Also, I would like to display the following name after the button is pressed. I have been trying to successfully implement this code for several days however, my program loads all names at once. Would anyone be able to provide advice about loading text files?
Below is a copy of my code:
firstName.Multiline = True 'Variable contains first name.
lastName.Multiline = True 'Variable contains last name.
Dim fullName = "" 'Variable containing full name found in text file
Dim lines = IO.File.ReadAllLines("input.txt") 'loading input file located in Debug folder.
For Each i As String In lines
Dim fullNames = lines.Where(Function(line) line.Contains(" "))
If fullNames.Any() Then
Dim fullNamesSplit = fullNames.Select(Function(line) line.Split(" "c))
Dim firstNames = fullNamesSplit.Select(Function(line) line(0))
Dim lastNames = fullNamesSplit.Select(Function(line) line(1))
firstName.Lines = firstNames.ToArray()
lastName.Lines = lastNames.ToArray()
fullName = String.Join(Environment.NewLine, fullNames)
Else
firstName.Text = ""
lastName.Text = ""
End If
displayInfo.Items.Add(fullName)
Next
There's no loop. Load the names into an array, initialise an index variable to 0 and load the name at that index. Each time you click the Button, increment the index and load the name at that index. Once you reach the end, you can either wrap to the beginning or tell the user there are no more names. If you don't want to wrap then an even better option would be to load the names into a queue and then just dequeue on each click.
I have been able to display the names in order however I did not use a looping structure. However, the names are output multiple times in the text box after the button is clicked.
Dim i As Integer = 0
Private Sub NextAvName_Click(sender As Object, e As EventArgs) Handles nextAvName.Click
firstName.Multiline = True 'Variable contains first name.
lastName.Multiline = True 'Variable contains last name.
Dim fullName = "" 'Variable containing full name found in text file
Dim lines = IO.File.ReadAllLines("input.txt") 'loading input file located in Debug folder.
lines = lines.ToArray
Dim element As String
element = lines(i)
Dim fullNames = element.Where(Function(line) element.Contains(" "))
If fullNames.Any() Then
Dim fullNamesSplit = fullNames.Select(Function(line) element.Split(" "c))
Dim firstNames = fullNamesSplit.Select(Function(line) line(0))
Dim lastNames = fullNamesSplit.Select(Function(line) line(1))
firstName.Lines = firstNames.ToArray()
lastName.Lines = lastNames.ToArray()
fullName = String.Join(Environment.NewLine, fullNames)
Else
firstName.Text = ""
lastName.Text = ""
End If
displayInfo.Items.Add(fullName)
i = i + 1
Related
I have a problem with a sorted TreeView. I select the last line of a text file, then I extract from this text file the last child node added in the TreeView. Where the shoe pinch is that I can't do it! I have tried with the number of lines in this file, but no results. In fact, I do a bit of everything (not of course) to get the selected node to coincide in the treeview and the displays in the text boxes. Below is a screenshot and my code! I don't know if I made myself understood correctly, my English is translated English. Thank you. Claude.
Dim NbLine As Integer = 0
Dim SR As System.IO.StreamReader = New System.IO.StreamReader(OuvrirFichier)
While Not SR.EndOfStream
SR.ReadLine()
NbLine += 1
End While
SR.Close()
Dim lastLine As String = File.ReadLines(OuvrirFichier, Encoding.UTF8) _
.Where(Function(f As String) (Not String.IsNullOrEmpty(f))).Last.ToString
Dim mytext As String = lastLine.Substring(17, 90)
If NbLine > 0 Then
Dim lignesDuFichier As String() = File.ReadAllLines(OuvrirFichier, Encoding.UTF8)
Dim derniereLigne As String = lignesDuFichier(lignesDuFichier.Length - 1)
TreeView1.Focus()
TreeView1.SelectedNode = TreeView1.Nodes(0).Nodes(lignesDuFichier.Length - 1)
End If
Comments in line.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim OuvrirFichier = "C:\Users\maryo\Desktop\Code\Test Empty Line.txt" '"path to file"
'At least you will only be reading the file once
Dim AllLines = File.ReadAllLines(OuvrirFichier)
Dim LinesWithContent = AllLines.Where(Function(s) s.Trim() <> String.Empty)
Dim lastLine = LinesWithContent.Last
Dim mytext As String = lastLine.Substring(17, 90)
Debug.Print(mytext) 'Just checking that you get what was expected
Dim NbLine = AllLines.Length
Dim derniereLigne As String = AllLines(NbLine - 1) 'Another variable to hold last line???
'But this time it could be a blank line.
TreeView1.Focus()
'This makes no sense. An index of a subNode base on the number of lines in the text file
'is supposed to be the SelectedNode
'Why would this be the last node added?
TreeView1.SelectedNode = TreeView1.Nodes(0).Nodes(NbLine - 1)
'You never test the equality of the SelectedNode with mytext
End Sub
I have an List in a different form , and the values that are located inside the text boxes are retrieved from a list in a different form , my problem is that i cannot delete the values all at once because they come from a view and i'm not allowed to change multiple tables all at once, so my solution is to create an array with all my text boxes and to turn the value to null 1 by 1 and save them individual so that i don't get that error.
I've tried different solutions like saving everything at once.
Private Sub Comando28_Click()
Dim strTextBoxes(1 To 5) As String
tbAplic = Me.TbUAplicacion.Value
tbUsr = Me.tbuUsuario.Value
tbMail = Me.tbuMailUsuario.Value
tbnmbre = Me.tbuNombrePersona.Value
tbAppld = Me.tbuApellidosPersona.Value
tbDni = Me.tbuDNIPersona.Value
Dim ITM As strTextBoxes.ITM
For Each ITM In strTextBoxes.ITM
If ITM = Not Null Then ITM = Null
Guardar_Click '<---- this is a macro which I use to save the items new value
Next ITM
End Sub
the error it gives me when pressing the button that should make the action is as follows:
the user-defined type has not been defined
Try this:
Private Sub Comando28_Click()
Dim strTextBoxes(1 To 5) As String
tbAplic = Me.TbUAplicacion.Value
tbUsr = Me.tbuUsuario.Value
tbMail = Me.tbuMailUsuario.Value
tbnmbre = Me.tbuNombrePersona.Value
tbAppld = Me.tbuApellidosPersona.Value
tbDni = Me.tbuDNIPersona.Value
Dim ITM As String
Dim Item As Long
For Item = LBound(strTextBoxes) To UBound(strTextBoxes)
ITM = strTextBoxes(Item)
If ITM <> "" Then ITM = ""
Guardar_Click '<---- this is a macro which I use to save the items new value
Next
End Sub
This is my code for inserting from textfile to array to labels, but I want to be able to assign a tag property onto some of the words or perhaps use the 'Answer' which is located a line below on my text file??
IndexNo = 0
Dim FileTerm As String = "D:\soccer.txt"
Dim FileNum As Integer = FreeFile()
FileOpen(FileNum, FileTerm, OpenMode.Input)
Do
Term(IndexNo) = LineInput(FileNum)
Answer(IndexNo) = LineInput(FileNum)
IndexNo = IndexNo + 1
Loop Until EOF(FileNum)
FileClose(FileNum)
Dim Obj As Object, Count As Integer = 0
For Each Obj In Me.Controls
If TypeOf Obj Is Label Then
MyLabels(Count) = Obj
Count = Count + 1
End If
Next
Dim Random1, Random2 As Integer
Dim TempTerm, TempAnswer As Object
For Count = 0 To 15
Randomize()
Random1 = Val(Int(16 * Rnd()))
Random2 = Val(Int(16 * Rnd()))
TempTerm = Term(Random1)
Term(Random1) = Term(Random2)
Term(Random2) = TempTerm
TempAnswer = Answer(Random1)
Answer(Random1) = Answer(Random2)
Answer(Random2) = TempAnswer
Count = Count + 1
Next
For Count = 0 To 15
MyLabels(Count).Text = Term(Count)
Next
If anyone has any ideas, the help is appreciated. Thanks
Even though your question is not very clear. From what I get, you want to have some way to keep your Labels and the corresponding Term and Answers in sync.
There are many ways to do this, but I would prefer to do it as below... the perfect VB.NET way as opposed to using any legacy VB6 techniques.
First declare a class that would keep our Term and Answers in one object. This is the equivalent of Type in VB6.
Public Class TermAnswer
Public Term As String
Public Answer As String
' you may add more fields/properties here if you wish to...
End Class
Now it is easy to code our solution.
' declare a Dictionary object with Label as key and the corresponding Term and Answers as values.
Dim TermAnswers As New Dictionary(Of Label, TermAnswer)
' this is a temporary List to hold our Term and Answers read from file until we randomize them.
Dim tempTermAnswers As New List(Of TermAnswer)
' Our Labels array... yes it is this easy :)
Dim myLabels() As Label = Me.Controls.OfType(Of Label)().ToArray
' read our file into the tempTermAnswers List
Dim FileTerm As String = "D:\soccer.txt"
Using reader As New IO.StreamReader(FileTerm)
While Not reader.EndOfStream
Dim ta As New TermAnswer
ta.Term = reader.ReadLine
ta.Answer = reader.ReadLine
tempTermAnswers.Add(ta)
End While
reader.Close()
End Using
' pick Term Answers from our tempTermAnswers List randomly and add them to our TermAnswers Dictionary
' we also set our Label text here, though you can loop separately too
Dim randomNumbers As New Random
Dim tempTerm As TermAnswer, randomNumber As Integer
For Each label In myLabels
randomNumber = randomNumbers.Next(0, tempTermAnswers.Count)
tempTerm = tempTermAnswers(randomNumber)
TermAnswers.Add(label, tempTerm)
tempTermAnswers.Remove(tempTerm)
label.Text = tempTerm.Term
Next
' now you have your term answers in a Dictionary, indexed by Label.
' you can get any of them by providing a Label on your form as key and get the corresponding Term and Answer as value.
' e.g. let us list the Label Name, Term and Answer in our debug window...
For Each label In myLabels
Debug.WriteLine(label.Name & " ... " & TermAnswers(label).Term & " ... " & TermAnswers(label).Answer)
Next
I'm currently using the following to read the contents of all text files in a directory into an array
Dim allLines() As String = File.ReadAllLines(txtfi.FullName)
Within the text files are only 6 lines that all follow the same format and will read something like
forecolour=black
I'm trying to then search for the word "forecolour" and retrieve the information after the "=" sign (black) so i can then populate the below code
AllDetail(numfiles).uPath = ' this needs to be the above result
I've only posted parts of the code but if it helps i can post the rest. I just need a little guidance if possible
Thanks
This is the full code
Dim numfiles As Integer
ReDim AllDetail(0 To 0)
numfiles = 0
lb1.Items.Clear()
Dim lynxin As New IO.DirectoryInfo(zMailbox)
lb1.Items.Clear()
For Each txtfi In lynxin.GetFiles("*.txt")
Dim allLines() As String = File.ReadAllLines(txtfi.FullName)
ReDim Preserve AllDetail(0 To numfiles)
AllDetail(numfiles).uPath = 'Needs to be populated
AllDetail(numfiles).uName = 'Needs to be populated
AllDetail(numfiles).uCode = 'Needs to be populated
AllDetail(numfiles).uOps = 'Needs to be populated
lb1.Items.Add(IO.Path.GetFileNameWithoutExtension(txtfi.Name))
numfiles = numfiles + 1
Next
End Sub
AllDetail(numfiles).uPath = Would be the actual file path
AllDetail(numfiles).uName = Would be the detail after “unitname=”
AllDetail(numfiles).uCode = Would be the detail after “unitcode=”
AllDetail(numfiles).uOps = Would be the detail after “operation=”
Within the text files that are being read there will be the following lines
Unitname=
Unitcode=
Operation=
Requirements=
Dateplanned=
For the purpose of this array I just need the unitname, unitcode & operation. Going forward I will need the dateplanned as when this is working I want to try and work out how to only display the information if the dateplanned matches the date from a datepicker. Hope that helps and any guidance or tips are gratefully received
If your file is not very big you could simply
Dim allLines() As String = File.ReadAllLines(txtfi.FullName)
For each line in allLines
Dim parts = line.Split("="c)
if parts.Length = 2 andalso parts(0) = "unitname" Then
AllDetails(numFiles).uName = parts(1)
Exit For
End If
Next
If you are absolutely sure of the format of your input file, you could also use Linq to remove the explict for each
Dim line = allLines.Where(Function(x) (x.StartsWith("unitname"))).SingleOrDefault()
if line IsNot Nothing then
AllDetails(numFiles).uName = line.Split("="c)(1)
End If
EDIT
Looking at the last details added to your question I think you could rewrite your code in this way, but still a critical piece of info is missing.
What kind of object is supposed to be stored in the array AllDetails?
I suppose you have a class named FileDetail as this
Public class FileDetail
Public Dim uName As String
Public Dim uCode As String
Public Dim uCode As String
End Class
....
numfiles = 0
lb1.Items.Clear()
Dim lynxin As New IO.DirectoryInfo(zMailbox)
' Get the FileInfo array here and dimension the array for the size required
Dim allfiles = lynxin.GetFiles("*.txt")
' The array should contains elements of a class that have the appropriate properties
Dim AllDetails(allfiles.Count) as FileDetail
lb1.Items.Clear()
For Each txtfi In allfiles)
Dim allLines() As String = File.ReadAllLines(txtfi.FullName)
AllDetails(numFiles) = new FileDetail()
AllDetails(numFiles).uPath = txtfi.FullName
Dim line = allLines.Where(Function(x) (x.StartsWith("unitname="))).SingleOrDefault()
if line IsNot Nothing then
AllDetails(numFiles).uName = line.Split("="c)(1)
End If
line = allLines.Where(Function(x) (x.StartsWith("unitcode="))).SingleOrDefault()
if line IsNot Nothing then
AllDetails(numFiles).uName = line.Split("="c)(1)
End If
line = allLines.Where(Function(x) (x.StartsWith("operation="))).SingleOrDefault()
if line IsNot Nothing then
AllDetails(numFiles).uOps = line.Split("="c)(1)
End If
lb1.Items.Add(IO.Path.GetFileNameWithoutExtension(txtfi.Name))
numfiles = numfiles + 1
Next
Keep in mind that this code could be really simplified if you start using a List(Of FileDetails)
I've got an app with numerous textboxes that's basically a form to fill out. There are several tabpages in a tab control. In saving the data, I simply loop through the textboxes, get their names and text and put that in a text file with a '|' as a seperator. That works great and I can see all my textboxes and the data in the text file. Now comes the problem. When I read the file back (to load saved data back into the form) it loops through the control name and changes the text to whatever was in the file. It works fine with the textboxes that are on the form, but fails when it gets to the first textbox that is on a tabpage. How can I fix that? And if there's a better way to save the data, I'm all ears.
Here's the code that writes the file:
Private Sub savefile(file As String)
Dim ctl As Control = Me
Dim sw As System.IO.StreamWriter
sw = My.Computer.FileSystem.OpenTextFileWriter(file, False)
Do
ctl = Me.GetNextControl(ctl, True)
If ctl IsNot Nothing Then
If TypeOf ctl Is TextBox Then
sw.WriteLine(ctl.Name.ToString.Substring(3) & "|" & ctl.Text)
End If
End If
Loop Until ctl Is Nothing
sw.Close()
End Sub
Here's the code that reads the file and updates the textboxes:
Private Sub ReadFile(filename)
Dim strfilename As String = filename
Dim num_rows, x, y As Integer
Dim strarray(1, 1) As String
Dim ctrl As Control = Me
'Check if file exist
If File.Exists(strfilename) Then
Dim tmpstream As StreamReader = File.OpenText(strfilename)
Dim strrecords() As String
Dim strfields() As String
'Load content of file to strLines array
strrecords = tmpstream.ReadToEnd().Split(vbCrLf)
' Redimension the array.
num_rows = UBound(strrecords)
ReDim strarray(num_rows, 2)
' Copy the data into the array.
For x = 0 To num_rows - 1
strfields = strrecords(x).Split("|")
For y = 0 To 1
strarray(x, y) = strfields(y)
Next
Next
' Display the data in listbox
For x = 0 To num_rows - 1
Dim tbxname As String = strarray(x, 0)
tbxname = Remove(tbxname) 'routine that removes invisible characters
tbxname = "tbx" & tbxname
MsgBox(tbxname) 'used to verify each file and which one fails
Me.Controls(tbxname).Text = strarray(x, 1)
Next
Else : MsgBox("File doesn't exist!")
End If
End Sub
I hope that's enough information. Thanks in advance for any help!!
I think the line Me.Controls(tbxname).text = strarray(x,1) does not address your TextBox in your tab control, you may need to find out how to address your textbox in the tab page.
Something like
Me.TabControl1.TabPages(0).Controls(tbxname).text = starray(x,1)