How to get an specified line in an textbox and get the text from that line in an string
Dim lines As String() = testing.Text.Split(Environment.NewLine)
then access the lines just like this
lines(0) // would be first line
You need to split the text box text into an array of strings based on the line separator and then, if you have enough lines, get the line from the array:
Dim asLines As String()
Dim wLineToGet As Integer = 2
asLines = TextBox1.Text.Split(New String() {Environment.NewLine}, StringSplitOptions.None)
If asLines IsNot Nothing AndAlso asLines.Length >= wLineToGet Then
MessageBox.Show("Line " & wLineToGet & " = " & asLines(wLineToGet - 1))
Else
MessageBox.Show("There are not enough lines in the textbox to retrieve line " & wLineToGet)
End If
Related
I have a problem in split multi line in that it only splits the first line. I want to split all the lines.
Dim a As String
Dim b As String
Dim split = TextBox1.Text.Split(":")
If (split.Count = 2) Then
a = split(0).ToString
b = split(1).ToString
End If
TextBox2.Text = a
TextBox3.Text = b
You have to iterate all the lines in the textbox
For Each Ln As String In TextBox1.Lines
If Not String.IsNullOrEmpty(Ln) Then
Dim Lines() As String = Ln.Split(":"c)
If Lines.Length = 2 Then
TextBox2.Text &= Lines(0) & Environment.NewLine
TextBox3.Text &= Lines(1) & Environment.NewLine
End If
End If
Next
Edit- Updated to include condition checking to prevent index exceptions.
Edi2- It should be mentioned that drawing your strings into these textbox controls can take some time, it's not my place to judge your requirement, but you could optimize the routine by using collection based objects or stringbuilder.
IE:
Dim StrBldrA As New Text.StringBuilder
Dim StrBldrb As New Text.StringBuilder
For Each Ln As String In TextBox1.Lines
If Not String.IsNullOrEmpty(Ln) Then
Dim Lines() As String = Ln.Split(":"c)
If Lines.Length = 2 Then
StrBldrA.Append(Lines(0) & Environment.NewLine)
StrBldrb.Append(Lines(1) & Environment.NewLine)
End If
End If
Next
TextBox2.Text = StrBldrA.ToString
TextBox3.Text = StrBldrb.ToString
This has been bugging me for a week and i do not see any other way. We have only been taught record data structures which is basic, FileOpen, WriteLine and etc. but i read MSDN and StreamWriter/Reader looks much more promising. This is an assignment/coursework and its essential for practically all parts of the program.
All i want to do is read line by line separating fields by a comma and define it as a variable. It would also help to be able to read the line without the quotes "", because right now when i read a password out with LineInput it reads it entirely "pass".
Private Sub StudentLogin()
Dim Filename As New StreamWriter("" & Register.StudentDirectory & "" & Username & ".txt")
Dim str As String = "This"
Dim lines() As String = str.Split(New String() {Environment.NewLine}, StringSplitOptions.None)
For Each line As String In lines
Dim columns() As String = line.Split(","c)
Firstname = columns(0)
Surname = columns(1)
Password = columns(2)
ClassID = columns(3)
Next
MessageBox.Show("" & ClassID & " " & Password & "")
End Sub
Text file:
"cem","polat","pass","class"
I just want to read the file - then each line, row by row, defining each column field which is in C:/Spellcheck/data/accounts/students/+filename+ and define a few variables.
I read through the lines of a text file but break on blank lines.
Using sr As New StreamReader(openFileDialog1.OpenFile())
Dim text As [String] = sr.ReadToEnd()
Dim lines As String() = text.Split(vbCrLf)
For Each line As String In lines
Dim cleanline = line.Trim()
Dim words As String() = cleanline.Split(" ")
For Each word As String In words
If word.StartsWith("a", True, Nothing) OrElse word.StartsWith("e", True, Nothing) OrElse word.StartsWith("i", True, Nothing) OrElse word.StartsWith("o", True, Nothing) OrElse word.StartsWith("u", True, Nothing) OrElse word.StartsWith("y", True, Nothing) Then
System.Console.Write(word & "ay ")
Else
Dim mutated As String = word.Substring(1, word.Length - 1)
mutated = mutated & word.Substring(0, 1) & "yay "
System.Console.Write(mutated)
End If
Next
System.Console.Write(vbLf)
Next
End Using
I am using this input.
I get this error:
What should I change to prevent this runtime error and continue processing?
Replace this:
System.Console.Write(vbLf)
With this:
Console.WriteLine()
For Each line As String In lines
If line.IsNullOrWhiteSpace() Then Exit For
you should do something like this to ensure that you don't have that error:
...
For Each word As String In words
If (word.Equals("")) Then
Continue For
End If
...
This will ensure you never attempt to translate an empty string
First I used StringSplitOptions.None for lines and words. It will remove the empty string splittings.
Dim lines As String() = text.Split(New String() {Environment.NewLine}, StringSplitOptions.None)
Then I replaced the If statement that checked if word.starsWith({vowels}) with its Regex equivalent. Also, you can use RegexOptions.IgnoreCase to make it case-insensitive. (Import Text.RegularExpressions)
If Regex.IsMatch(word, "^[aeiouy]", RegexOptions.IgnoreCase) Then
Lastly, I added an If to check if word.Length > 0 before trying to access word(1).
Here's my final code:
Using sr As New StreamReader(OpenFileDialog1.OpenFile())
Dim text As String = sr.ReadToEnd()
Dim lines As String() = text.Split(New String() {Environment.NewLine}, StringSplitOptions.None)
For Each line As String In lines
Dim cleanline As String = line.Trim()
Dim words As String() = cleanline.Split(New Char() {" "c}, StringSplitOptions.None)
For Each word As String In words
If Regex.IsMatch(word, "^[aeiouy]", RegexOptions.IgnoreCase) Then
System.Console.WriteLine(word & "ay ")
ElseIf word.Length > 0 Then
Dim mutated As String = word(1) & word(0) & "yay "
System.Console.WriteLine(mutated)
End If
Next
Next
End Using
I want to know how to read and convert the different lines of a richtextbox in vb.net
for example if these are the lines of a RichTextBox:
Hello
Hi
How can I convert it to something like:
Yo(Hello)
Yo(Hi)
and put the result in a second richtextbox?
RichtextBox has a lines property:
Dim rtb_in As New RichTextBox
Dim rtb_out As New RichTextBox
For Each line In rtb_in.Lines
rtb_out.AppendText(String.Format("Foo({0})", line))
Next
Always a good idea to check out MSDN for the classes you work with ...
You could try splitting on a new line and modifying the results:
Dim box1Lines as String() = richTextBox1.Text.Split(new String() { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)
Dim newLines as String = ""
For Each line As String in box1Lines
newLines += "Yo(" & line & ")" & Environment.NewLine
Next
richTextBox2.Text = newLines
Possibly you should use String.Join to accomplish it. A one line solution would be:
rtbOut.Lines = ("Yo(" & String.Join(")" & Environment.NewLine & "Yo(", rtbIN.Lines) & ")").Split(Environment.NewLine.ToCharArray, StringSplitOptions.RemoveEmptyEntries)
and here is the complete code where modified line is assigned to second RichTextBox:
Dim rtbIN As New RichTextBox
Dim rtbOut As New RichTextBox
rtbIN.Lines = New String() {"Hello ", "Hi"}
rtbOut.Lines = ("Yo(" & String.Join(")" & Environment.NewLine & "Yo(", rtbIN.Lines) & ")").Split(Environment.NewLine.ToCharArray, StringSplitOptions.RemoveEmptyEntries)
I have the following text file (ExamMarks.txt)
John, 85, 95, 90
Micheal, 60, 75, 75
I want to extract a line and take the Name and separately and the ints separately. Then I want to print the name and the average of the numbers like this in a label:
John's average is 90
Micheal's average is 70
So far I can only display what is in the text file in a label (see below):
Dim FILE_NAME As String = "C:\ExamMarks.txt"
Dim TextLine As String
If System.IO.File.Exists(FILE_NAME) = True Then
Dim objReader As New System.IO.StreamReader(FILE_NAME)
Do While objReader.Peek() <> -1
TextLine = TextLine & objReader.ReadLine & vbNewLine
Loop
lblResults.Text = TextLine
Else
MsgBox("File Does Not Exist")
End If
Any help is appreciated.
Do this processing for each of the lines in the file. It assumes that the name is always the first word in the string, then it calculates the average of all the numbers in the string.
'Split the test string on commas
Dim strScores() As String = strTest.Split(",".ToCharArray)
Dim strWord As String
Dim intTotalScore As Integer
Dim intCountOfScores As Integer
Dim intAverageScore As Integer
'Name is the first word in the line
strName = strScores(1).Trim
For Each strWord In strScores
If IsNumeric(strWord) Then
intTotalScore = intTotalScore + Int(strWord.Trim)
intCountOfScores = intCountOfScores + 1
End If
Next
'Calculate the average
intAverageScore = intTotalScore / intCountOfScores
You can do all this much more briefly with some more modern code:
Use the built-in TextFieldParser to read the comma-separated file, and access each row as a string array. It's simpler and more robust than using Split.
And then use IEnumerable extension methods to calculate the average all in one line.
a. Skip(1) skips the first entry.
b. Average() lets you convert the remaining entries to Double and then take the average.
Like this:
Sub Main()
Using MyReader As New _
Microsoft.VisualBasic.FileIO.TextFieldParser("ExamMarks.txt")
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(",")
Dim currentRow As String()
While Not MyReader.EndOfData
Try
' Read row as an array of strings '
currentRow = MyReader.ReadFields()
' Calculate average '
Dim dAverage As Double = _
currentRow.Skip(1).Average(Function(s) Convert.ToDouble(s))
' Write out result '
Console.WriteLine(currentRow(0) & "'s average is " & _
Convert.ToString(dAverage))
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & "is not valid and will be skipped.")
End Try
End While
End Using
Console.ReadLine()
End Sub