Locate of the string in a multi-line textbox? - vb.net

For example, if we write:
Textbox1.Text = "Hello"
If the textbox is MultiLine, how can we control the location of the string in 2nd line of the textbox?

What means control? Do you want to locate the indices or do you want to replace a line with this text?
If you want to determine the line(s) with the text "Hello":
Dim lineIndices = textbox1.Lines.
Select(Function(line, index) New With { .Line = line, .Index = index }).
Where(Function(x) x.Line.Contains("Hello")).
Select(Function(x) x.Index)
If you want to replace a line of a textbox with a given text:
Dim index As Int32 = 1 ' second line '
If textbox1.Lines.Length > index Then
textbox1.Lines(index) = "Hello"
Else
Dim emptyLines = index - textbox1.Lines.Length
textbox1.Lines = textbox1.Lines.
Concat(Enumerable.Repeat("", emptyLines)).
Concat({"Hello"}).ToArray()
End If

Related

How to get number of line of a specific word in it in multiline textbox in vb .net

I have a multiline text box and I want to get line number that specific word in it.
I tried this:
For Each line As String In TextBox1.Lines
If line = "50" Then
Label2.Text = 'Number Of line
End If
Next
But I don't know how to get line number that "50" in it and show it in label2.
how can i do that?
Try using a counter:
Dim iLineCount As Integer = 0
For Each line As String In TextBox1.Lines
iLineCount += 1
If line = "50" Then
Label2.Text = iLineCount.ToString()
End If
Next
Use a For-loop instead of a For Each:
Dim lines = TextBox1.Lines
For i As Int32 = 0 To lines.Length - 1
If lines(i) = "50" Then Label2.Text = (i + 1).ToString()
Next
I'm storing the TextBox.Lines String() in a variable because there's some overhead if you use this property often.
Or try this:
Dim lines = TextBox1.Lines
Label2.Text = Array.IndexOf(lines, "50").ToString()
That will show the (zero based) index of first line to contain "50". Or -1 if no matching lines found.

Load textfile containing names to a textbox

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

Remove a line of text where the cursor is positioned

All my below code remove all blank lines from TextBox.
But I want the cursor pointed line to get removed when clicked on button.
'First method
TextBox2.Lines = TextBox2.Lines.Where(Function(l) Not String.IsNullOrWhiteSpace(l)).ToArray()
Dim count = TextBox2.Lines.Length
'Second method
Dim tmp() As String = TextBox2.Text.Split(CChar(vbNewLine))
TextBox2.Clear()
For Each line As String In tmp
If line.Length > 1 Then
TextBox2.AppendText(line & vbNewLine)
End If
Next
'Third method
Dim SearchIn = Me.TextBox2.Text
Dim sb As StringBuilder = New StringBuilder(SearchIn)
Me.TextBox2.Text = sb.Replace(vbCrLf + vbCrLf, vbCrLf).ToString
'Fourth method
TextBox2.Text = Regex.Replace(TextBox2.Text, "(?<Text>.*)(?:[\r\n]?(?:\r\n)?)", "${Text} ") + "/n"
TextBox2.Text = Replace(TextBox2.Text, vbCrLf & vbCrLf, vbCrLf)
To remove a line of text from a TextBoxBase derived control (TextBox, RichTextBox), you first have to identify the correct line.
You can't use the .Lines property if the Text is wrapped, because it will return the line number relative to the unwrapped text.
You can get the current wrapped line with GetLineFromCharIndex(). The Integer parameter is the current caret position, referenced by the SelectionStart property.
The first character index of this line is retured by GetFirstCharIndexFromLine().
Then, find the current line lenght, identifying the first line feed. Add the lenght of the line feed symbol(s) to include them in the computed lenght.
Note that TextBox controls use Environment.Newline to generate a line feed ("\r\n"), while RichTextBox controls use only a line feed ("\n").
This will remove any line where the caret is currently positioned:
(If you just want to allow blank lines to be removed, check whether the line lenght is < 3).
Dim CurrentPosition As Integer = TextBox2.SelectionStart
Dim CurrentLine As Integer = TextBox2.GetLineFromCharIndex(CurrentPosition)
Dim LineFirstChar As Integer = TextBox2.GetFirstCharIndexFromLine(CurrentLine)
Dim LineLenght As Integer = TextBox2.Text.
IndexOf(Environment.NewLine, LineFirstChar) - LineFirstChar +
Environment.NewLine.Length
If LineLenght <= 0 Then Return
TextBox2.Select(LineFirstChar, LineLenght)
TextBox2.SelectedText = TextBox2.SelectedText.Remove(0)
TextBox2.SelectionLength = 0
TextBox2.SelectionStart = If(CurrentPosition < TextBox2.Text.Length, LineFirstChar, TextBox2.Text.Length)
TextBox2.Focus()
This will instead remove the whole paragraph that contains the caret:
Dim CurrentPosition As Integer = TextBox2.SelectionStart
Dim ParagraphFirstIndex As Integer = TextBox2.Text.
LastIndexOf(Environment.NewLine, CurrentPosition) +
Environment.NewLine.Length
Dim LineFeedPosition As Integer = TextBox2.Text.IndexOf(Environment.NewLine, ParagraphFirstIndex)
LineFeedPosition = If(LineFeedPosition > -1, LineFeedPosition + Environment.NewLine.Length, TextBox2.Text.Length)
Dim LineLenght As Integer = LineFeedPosition - ParagraphFirstIndex
If LineLenght <= 0 Then Return
TextBox2.Select(ParagraphFirstIndex, LineLenght)
TextBox2.SelectedText = TextBox2.SelectedText.Remove(0)
TextBox2.SelectionLength = 0
TextBox2.SelectionStart = If((CurrentPosition < TextBox2.Text.Length), ParagraphFirstIndex, TextBox2.Text.Length)
TextBox2.Focus()

Showing the difference between two RichTextBox controls

I'm trying to compare both richtextbox text and show the difference into the 3rd richtextbox. After i do some changes to the code that i get from this forum, it still have some problems, which is there are words that are no different showing out at my 3rd richtextbox.... the right hand side of the rich text box is from a text file that have been checked in regex function before displayed in the box.
this is the source code that use for compare:
Dim txt1(DispBox.Text.Split(" ").Length) As String
Dim txt2(DispBox2.Text.Split(" ").Length) As String
txt1 = DispBox.Text.Split(" ")
txt2 = DispBox2.Text.Split(" ")
Dim diff1 As String = "" 'Differences between 1 and 2
Dim diff2 As String = "" 'Differences between 2 and 1
Dim diffPosition As Integer ' Set where begin to find and select in RichTextBox
diffPosition = 1 ' Initialize
For Each diff As String In txt1
If Array.IndexOf(txt2, diff.ToString) = -1 Then
diff1 += diff.ToString & " "
With DispBox
.Find(diff, diffPosition, RichTextBoxFinds.None) ' Find and select diff in RichTextBox1 starting from position diffPosition in RichtextBox1
.SelectionFont = New Font(.Font, FontStyle.Bold) ' Set diff in Bold
.SelectionColor = Color.Blue ' Set diff in blue instead of black
.SelectionBackColor = Color.Yellow ' highlight in yellow
End With
End If
diffPosition = diffPosition + Len(diff) ' re-Initialize diffPostion to avoid to find and select the same text present more than once
Next
DispBox3.Visible = True
DispBox3.Text = diff1
this is my upload button code to check the regex function
Dim result As DialogResult = OpenFileDialog1.ShowDialog()
' Test result.
If result = Windows.Forms.DialogResult.OK Then
' Get the file name.
Dim path As String = OpenFileDialog1.FileName
Try
' Read in text.
Dim text As String = File.ReadAllText(path)
Dim postupload As String = Regex.Replace(text, "!", "")
DispBox2.Text = postupload
' For debugging.
Me.Text = text.Length.ToString
Catch ex As Exception
' Report an error.
Me.Text = "Error"
End Try
End If
because inside the text file there will be "!" between the line, I would like to replace the "!" with "breakline/enter".
My problem is :
why the "Building & hostname" words count as wrong words.
why the new word that display in 3rd richtextbox is not in new line if the words is found in the middle of the line.
the other wrong words are not color, bold n highlight.....
Your code is splitting all the words based on a space, but it's ignoring the line breaks, so it makes "running-confing building" look like one word.
Try it this way:
Dim txt1 As String() = String.Join(" ", DispBox.Lines).Split(" ")
Dim txt2 As String() = String.Join(" ", DispBox2.Lines).Split(" ")

VB.NET RichTextBox and TextBox Separation

For my company, we receive our time sheets in the following format
Name:Hours
Name:Hours
Name:Hours
I have the Timesheet.txt loading into the RichTextBox1 fine, but, I want when I click a button to load them into two different textboxes. I want the Names to load into TextBox1 and Hours to load into TextBox2
Then it deletes the line. It will go onto the next line when I click the button again.
Any help?
Simple, but will do:
Dim sInput As String = "Name:10"
Dim sSplitArray() As String = sInput.Split(New Char() {":"c})
Dim sName As String = sSplitArray(0)
Dim sHours As String = sSplitArray(1)
String's Split function splits a string up by the character you pass to it.
So if you have this:
sInput = "Name:10:Zebra:Kazaam"
When you split that string by the ":" separator, it will give you an array with:
Name
10
Zebra
Kazaam
Hope that this will give the complete solution for your problem
Dim x, y As Integer
Dim textbox1() As TextBox
x = 430
y = 265
Dim str As String
Dim result(), output(1) As String'str=RitchText1.text 'load input string to str
result = str.Split(System.Environment.NewLine) ' split into array based on new line
For i As Integer = 0 To result.Length - 1 'execute up to array limit
output = result(i).Split(":") 'split again based on :
textbox1(i).Text = output(0) 'Name part into dynamic textbox 1
textbox1(i).Location = New Point(x, y)
textbox1(i + 1).Text = output(1) 'Name part into dynamic textbox 2
textbox1(i + 1).Location = New Point(x + 40, y)
Me.Controls.Add(textbox1(i))
textbox1(i).Visible = True
Me.Controls.Add(textbox1(i + 1))
textbox1(i + 1).Visible = True
y = y + 20
Next