Search string to add line after specific word in VB.net - vb.net

(I am a VERY basic programmer)
I have a body of text which needs searching through to find a specific word "Customer" and then save the next line as the CustomerName (CustomerName = >line of text<)

If your "body of text" is a TextBox you could take profit of the .Lines property:
Dim index As Integer
Dim customerName As String = ""
For i As Integer = 1 to TextBox1.Lines.Length - 1
If TextBox1.Lines(i-1).Contains("Customer") Then
customerName = TextBox1.Lines(i)
Exit For
End If
Next
If you have a plain text, you can obtain the lines splitting the whole text:
Dim lines() As String = sAllText.Split(Environment.NewLine())
And then doing the same as before, but instead of using TextBox1.Lines, use lines.

Related

VB.net Read Specific Lines From a Text File That Start With and Stop Reading When Start With

I'm looking to read lines from a text file that start with certain characters and stop when the line starts with other characters. So in my example I would like to start reading at line AB and stop at line EF however not all lines will contain the CD line. There will always be a AB line and EF line, however the number of lines in between is unknown.
Here is an example of the lines in a text file I would be reading. You can see that this will create two rows in the DataGridView however the first row is missing the CD line and should be blank.
AB-id1
EF-address1
AB-id2
CD-name1
EF-address2
Here is the code I have so far:
Dim lines() As String = File.ReadAllLines(textfile)
For i As Integer = 0 To lines.Length - 1
If lines(i).StartsWith("AB") Then
Dim nextLines As String() = lines.Skip(i + 1).ToArray
Dim info As String = nextLines.FirstOrDefault(Function(Line) Line.StartsWith("CD"))
Dim name As String = "Yes"
Dim info2 As String = nextLines.FirstOrDefault(Function(Line) Line.StartsWith("EF"))
Dim address As String = "Yes"
End If
DataGridView.Rows.Add(name,address)
Next
Now the output I currently get is:
|Yes|Yes|
|Yes|Yes|
And I should be getting:
||Yes|
|Yes|Yes|
It looks like it's reading too far down the text file and I need it to stop reading at EF. I've tried Do while and Do Until with no success. Any suggestions?
You could use the Array.FindIndex function to get the index of the next line starting with your prefix. This way you don't have to skip lines and create a new array each time.
Try this out instead:
Dim lines() As String = File.ReadAllLines(textFile)
For i As Integer = 0 To lines.Length - 1
If lines(i).StartsWith("AB") Then
Dim addressIndex As Integer = Array.FindIndex(lines, i + 1, Function(Line) Line.StartsWith("EF"))
Dim address As String = If(addressIndex <> -1, lines(addressIndex).Substring(3), "") ' Get everything past the "-"
Dim name As String = ""
If addressIndex <> -1 Then
Dim nameIndex As Integer = Array.FindIndex(lines, i + 1, addressIndex - i, Function(line) line.StartsWith("CD"))
If nameIndex <> -1 Then
name = lines(nameIndex).Substring(3) ' Get everything past the "-"
End If
End If
DataGridView.Rows.Add(name, address)
End If
Next

VB.Net , Finding data in a text file by ID number

I'm using the VB.net forms application for this project.
so I have a text file like this
7,John,Kimberlake,john#mail.com,27,Bachelor
8,Tiny,Down,tiny#mail.com,34,Master
9,Jeniffer,Kime,Jen#mail.com,22,None
I have 1 textbox and 1 button.
The purpose is that you need to fill an id number to find the data about the person.
Dim Findstring = IO.File.ReadAllText("data.txt")
Dim Data As String = TextBox1.Text
Dim aryTextFile() As String
aryTextFile = Findstring.Split(",")
If aryTextFile.Contains(Data) Then
End If
I tried this and something like finding the index number in the array of the requested id but it didn't work.
Instead of ReadAllText use ReadLines and loop each line to get the data.
Walk through below code and comments.
There are much better ways to do this, But the below is very basic way of doing for easy understanding.
'READ EACH LINE OF THE TEXT FILE.
For Each item As String In IO.File.ReadLines("C:\\Desktop\\test.txt") 'ENSURE VALID PATH HERE
'THIS IS EACH LINE.
Dim Findstring = item
'ASSUME THIS IS TEXT ID FROM TEXT BOX.
Dim ID As String = "8"
'SPLIT THE LINE BASED ON ","
Dim aryTextLine() As String
aryTextLine = Findstring.Split(",")
'NOW YOU HAVE ARRAY TO READ EACH ITEM.
If aryTextLine(0) = ID Then
Dim name = aryTextLine(1)
End If
Next

How do I add text to a specific line in a text file in visual basic?

I am trying to create a program for an a level project using visual studio 2010 or 2017 at home, and am using a console application. What I need it to do is to create a text file with the students details which are entered to the program by the teacher. Then the teacher needs to be able to enter a specific student ID number and be able to add a score to the end of the record for this student.
This is my code so far and works as it should. But it only allows the teacher to enter the students details and writes it to the text file.
Dim studentID As String
Dim studentname As String
Dim classname As String
Dim Filename As String
Filename = “Students.txt”
FileOpen(1, Filename, OpenMode.Append)
Console.WriteLine(" Student Setup")
Console.WriteLine()
Console.WriteLine()
Console.Write("Student ID: ")
studentID = Console.ReadLine
Console.Write("Student Name: ")
studentname = Console.ReadLine
Console.WriteLine()
Console.Write("Class : ")
classname = Console.ReadLine
WriteLine(1, studentID, studentname, classname)
Console.WriteLine("Student successfully setup.")
Now I want to be able to allow the teacher to type in a students ID number and a score, and then write the score to the end of the specific line in the text file which begins with the students ID number.
An example of the text file will look like this:
"12345","Adam","A"
"67534","Alice","A"
"21456","Bob","A"
"98765","Charles","A"
"87654","Dennis","A"
Then if the teacher types in 21456 as the students ID number to add score to, and a score of 6 then it will add the number 6 to the end of this line, so that the line of the text file will now look like this:
"21456","Bob","A","6"
I have attempted to do this with the following code, which I got from another forum and tried to alter to do what I wanted to do:
Dim score As Integer
Dim studentIDenter As String
Dim count As Integer
Console.Write("Student ID to add score to: ")
studentIDenter = Console.ReadLine
Console.Write("Student score: ")
score = Console.readline
Dim lines() As String = System.IO.File.ReadAllLines(Filename)
For count = 0 To lines.Length - 1
If lines(count).StartsWith(studentIDenter) Then
lines(count) = studentID & studentname & classname & score
System.IO.File.WriteAllLines(Filename, lines)
End If
Next
FileClose(1)
I assume the user is NOT entering quotes around the student number and score.
You need to add the quotes in your check for a match at the beginning of the line. Additionally, you need to add a comma and quotes around the score when you add them to the end of the line.
Change to:
For count = 0 To lines.Length - 1
If lines(count).StartsWith(Chr(34) & studentIDenter & Chr(34)) Then
lines(count) = lines(count) & "," & Chr(34) & score & Chr(34)
System.IO.File.WriteAllLines(Filename, lines)
Exit For ' found the record, no need to keep looking
End If
Next
I have created the following:
Sub Main()
Dim studentID As String
Dim studentname As String
Dim classname As String
Dim addScoreSelection As String
Dim inputSID As String
Dim Filename As String
Filename = “Students.txt”
FileOpen(1, Filename, OpenMode.Append)
Console.WriteLine("Add a Score? Y/N")
addScoreSelection = Console.ReadLine.ToLower()
If addScoreSelection = "Y".ToLower() Then
FileClose(1)
Console.WriteLine("Enter a student ID: ")
inputSID = Console.ReadLine()
AddScore(inputSID)
ElseIf addScoreSelection = "N".ToLower() Then
Console.WriteLine("Student Setup")
Console.WriteLine()
Console.WriteLine()
Console.Write("Student ID: ")
studentID = Console.ReadLine
Console.Write("Student Name: ")
studentname = Console.ReadLine
Console.WriteLine()
Console.Write("Class : ")
classname = Console.ReadLine
WriteLine(1, studentID, studentname, classname)
Console.WriteLine("Student successfully setup.")
Else
Console.WriteLine("No selection made. Exiting.")
Process.GetCurrentProcess.Kill()
End If
End Sub
Sub AddScore(ByVal ID As String)
Dim Filename As String
Filename = “Students.txt”
Dim fileContent As String()
Dim index As Integer = 0
fileContent = IO.File.ReadAllLines(Filename)
For Each line As String In fileContent
If line.Contains(ID) Then
fileContent(index) = fileContent(index) & ",""6""" 'Pass in a ByVal param for this
Exit For
End If
index += 1
Next
IO.File.WriteAllLines(Filename, fileContent)
End Sub
I have added the sub routine AddScore that takes a student ID as a string param, I then use this parameter in a .Contains() to determine WHEN I have hit the line we are interested in in the text file.
I create a string array by reading all the text from the file
fileContent = IO.File.ReadAllLines(Filename)
I iterate through the array looking for the line in question, once the line is found I append the score to the end of the line (You will probably want to actually use a param here)
For Each line As String In fileContent
If line.Contains(ID) Then
fileContent(index) = fileContent(index) & ",""6""" 'Pass in a ByVal param for this
Exit For
End If
index += 1
Next
I then write the string array to the file
IO.File.WriteAllLines(Filename, fileContent)
This solves your issue I believe, but personally I am not happy with this. I don't like the idea of grabbing a whole lot of text and putting it into memory (imagine if we were reading a 5GB file...). The best solution in the long run would be to use the FileStream class to read/write it and find the line and append the text on said line.

Replace text in textbox without using replace function

This is more like a logical question, I just need an idea on how to best approach this problem.
I am trying to do this in visual basic. I have to text box, in text box 1, I would have some text and if it contains certain word, I want to replace that with something else and have the new output in text box 2, after clicking on a convert button.
I know this can be done really easily with the replace function built in, but I am trying to do it without the replace function.
For example:
I want to replace "fox" with "dog"
Textbox 1: The quick brown fox jumped over the lazy dog.
Textbox 2: The quick brown dog jumped over the lazy dog.
I got it to work with the code below, but this only works for the first instance. How can I change my code for all instances.
String from InputText
Dim S1 As String
S1 = InputText.Text
'Position of start of "Edge Computer"
Dim pStart As Integer
pStart = S1.IndexOf("Edge Computer")
'Position of end of "Edge Computer"
Dim pEnd As Integer
pEnd = S1.IndexOf("r", pStart) + 1
'Actual old name as string
Dim strOld As String
strOld = S1.Substring(pStart, 13)
'New String for Output
Dim S2 As String
S2 = S1.Substring(0, pStart) & "3dg3" & S1.Substring(pEnd)
OutputText.Text = S2
Thanks
If you don't want to use replace you could use substring to select the text before and after the word that as to be replaced.
You did not post any code so it's hard to put an example that would fit you better
Dim NewText as String
If textbox1.text.IndexOf("OldWord") > - 1 Then
NewText = textbox1.text.Substring(0, textbox1.text.IndexOf("OldWord")) & "NewWord " & textbox1.text.Substring(textbox1.text.IndexOf("OldWord") + "Something".length, textbox1.text.length )
'Make sure you replacfe OldWold and NewWord to the specific text or variable
End If
To make it work with all instance of the word, you just need to replace the if by a loop
Dim NewText as String
Dim OldText as String = textbox1.text
While OldText.IndexOf("OldWord") > - 1
NewText = OldText.Substring(0, OldText.IndexOf("OldWord")) & "NewWord " & OldText.Substring(OldText.IndexOf("OldWord") + "OldWord".length, OldText.length )
OldText = OldText.Substring(OldText.IndexOf("OldWord") + "OldWord".length, OldText.length)
'Make sure you replace OldWold and NewWord to the specific text or variable
End While
Let me know if this works or not

How do I manipulate the last string of a Richtextbox in Visual Basic

I am trying to take a string in a rich text box and replace them with a different string.
Now how this should work is that if two same characters are entered into the text box
e.g tt the "tt" will be replaced with "Ǿt" , it adds back one of the t's to the replaced string. Only the most recently entered string is manipulated if two same characters are entered .
I read the LAST string that is in the RichTextBox by using this method
Dim laststring As String = RichTextBox1.Text.Split(" ").Last
'hitting space bar breaks the operation so if i enter t t there will be no replacement
this is the replacement method which I use , it works correctly .
if laststring = "tt"
RichTextBox1 .Text = RichTextBox1 .Text.Replace("tt", "Ǿt")
This method is inefficient because i need to check id there are double letters for all letters and if i was to use this method it would tavke up a lot of code .
how can I accomplish this using a shorter method??
You need to put the if then section in a loop.
Dim holdstring As String
Dim doubleinstance() As String = {"bb", "tt", "uu"} ' array
Dim curstring As String = RichTextBox1.Text.Split(" ").Last
For Each item As String In doubleinstance
If RichTextBox1.Text.EndsWith(item) Then
holdstring = RichTextBox1.Text.Split(" ").Last.Length - 1 ' change to subtract 1 character from doubleinstance
RichTextBox1.Text = RichTextBox1.Text.Replace(curstring, "Ǿt" & holdstring)
MsgBox(curstring)
End If
Next item
Here's a bit of code to get you in the right direction...
There are a couple of variations of .Find, but you probably want to look at the .Select method.
With RichTextBox1
.Find("Don")
.SelectedText = "Mr. Awesome"
End With
Here is a way I came up with
Dim holdstring As String
Dim doubleinstance() As String = {"bb", "tt", "uu"} ' array
Dim curstring As String = RichTextBox1.Text.Split(" ").Last
If curstring = doubleinstance(0) And RichTextBox1.Text.EndsWith(doubleinstance(0)) Then
holdstring = RichTextBox1.Text.Split(" ").Last.Length - 1 ' change to subtract 1 character from doubleinstance
RichTextBox1.Text = RichTextBox1.Text.Replace(curstring, "Ǿt" + holdstring)
MsgBox(curstring)
End If
where i have doubleinstance(0) how do i get the if statement to not only check a single index but all of the index from 0 to 2 in this example ?