Remove a line of text where the cursor is positioned - vb.net

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

Related

How to join selected lines in a RichTextBox with a specific character and replace the existing lines?

I want to join selected line in RichTextBox and separate those two lines with specific character.
The situation is dire
But momma raised up a fighter
It's all come down to the wire
But the come-up is higher
result:
The situation is dire - But momma raised up a fighter
or
It's all come down to the wire - But the come-up is higher
The new line generated should replace the existing lines in the Control.
Try this:
Dim StartSelection As Integer = RichTextBox1.SelectionStart
Dim EndSelection As Integer = RichTextBox1.SelectionStart + RichTextBox1.SelectionLength
Dim StartLine As Integer = 0
Dim EndLine As Integer = 0
Dim Position As Integer = 0
Dim Pos As Integer = 0
Dim Index As Integer = 0
For i = 0 To RichTextBox1.Lines.Length - 1
Position += RichTextBox1.Lines(i).Length
If StartSelection <= Position Then
StartLine = i
Exit For
End If
Next
Position = 0
For i = 0 To RichTextBox1.Lines.Length - 1
Position += RichTextBox1.Lines(i).Length
If Position >= EndSelection Then
EndLine = i
Exit For
End If
Next
If EndLine = 0 Then
EndLine = RichTextBox1.Lines.Length - 1
Else
EndLine -= 1
End If
If Not StartLine = EndLine Then
Do
Pos += RichTextBox1.Lines(Index).Length
If Index = StartLine Then
Exit Do
Else
Index += 1
End If
Loop
Pos -= RichTextBox1.Lines(Index).Length
For i = StartLine To EndLine - 1
If i = StartLine Then
RichTextBox1.Text = RichTextBox1.Text.Remove(Pos + RichTextBox1.Lines(Index).Length + i, 1).Insert(Pos + RichTextBox1.Lines(Index).Length + i, " - ")
RichTextBox1.Refresh()
Else
RichTextBox1.Text = RichTextBox1.Text.Remove(Pos + RichTextBox1.Lines(Index).Length + StartLine, 1).Insert(Pos + RichTextBox1.Lines(Index).Length + StartLine, " - ")
RichTextBox1.Refresh()
End If
Next
End If
I recommend placing the code in the mouse-up event of the Textbox or RichTextbox.
An example using both string.Join() and LINQ's Aggregate() methods, to fill a StringBuilder that acts as an accumulator for the lines of text.
A StringBuilder object is a convenient storage when dealing with strings, it can limit the number of strings that will need garbage collection after use.
LINQ's Skip() and Take() method are also used to Skip the specified number of elements in a collection and Take a specified number of elements.
Note that Take() doesn't overflow: if the number of elements to take is more than what's available, it just takes what it can find.
I've mixed string.Join() and Aggregate() to show their use, you can actually perform all actions using one or the other.
Using Aggregate(), the last chars in the StringBuilder are determined by Environment.NewLine and need to be removed.
Note that the StringBuilder.ToString() method allows to generate a sub-string of the content.
If you use String.Join() instead, you don't need to strip the trailing chars.
You can call the MergeLines() method as:
RichTextBox1.Text = MergeLines(RichTextBox1.Text, 1, 4)
to merge 4 the lines of text in a RichTextBox, from line 1 to line 4.
If you have 6 lines and you want to merge all, then specify:
RichTextBox1.Text = MergeLines(RichTextBox1.Text, 0, 5)
The method checks whether the starting and ending lines specified express line values that are compatible with the content of the text.
Imports System.Linq
Imports System.Text
Private Function MergeLines(text As String, lineStart As Integer, lineEnd As Integer) As String
Dim lines = text.Split(ControlChars.Lf)
If lines.Length < 2 OrElse (lineStart < 0 OrElse lineEnd >= lines.Length) Then Return text
Dim sb = lines.Take(lineStart).
Aggregate(New StringBuilder(), Function(s, ln) s.AppendLine(ln))
sb.AppendLine(String.Join(" - ", lines.Skip(lineStart).Take(lineEnd - lineStart + 1)))
lines.Skip(lineEnd + 1).Aggregate(sb, Function(s, ln) s.AppendLine(ln))
Return sb.ToString(0, sb.Length - Environment.NewLine.Length)
End Function
Description of the first line of code that aggregates string elements to a StringBuilder:
Dim sb = lines.
Take(lineStart).
Aggregate(New StringBuilder(),
Function(s, ln) s.AppendLine(ln)
Using the lines collection:
Take lineStart number of lines. lineStart is the first line to merge: if lineStart = 2 - the third line - then take 2 lines, thus lines 0 and 1).
Aggregate in a new StringBuilder object each line taken. The StringBuilder appends each line plus Environment.NewLine.
The result of the aggregation is a filled StringBuilder object.
C# version:
private string MergeLines(string text, int start, int end)
{
var lines = text.Split('\n'); ;
if (lines.Length < 2 || (start < 0 || end >= lines.Length)) return text;
var sb = lines.Take(start).Aggregate(new StringBuilder(), (s, ln) => s.AppendLine(ln));
sb.AppendLine(string.Join(" - ", lines.Skip(start).Take(end - start + 1)));
lines.Skip(end + 1).Aggregate(sb, (s, ln) => s.AppendLine(ln));
return sb.ToString(0, sb.Length - Environment.NewLine.Length);
}

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.

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

How To Replace or Write the Sentence Backwards

I would like to have a block of code or a function in vb.net which can write a sentence backwards.
For example : i love visual basic
Result : basic visual love i
This is what I have so far:
Dim name As String
Dim namereversed As String
name = RichTextBox1.Text
namereversed = ""
Dim i As Integer
For i = Len(name) To 1 Step -1
namereversed = namereversed & Replace(name, i, 1)
Next
RichTextBox2.Text = namereversed
The code works but it does not give me the value of what i want. it makes the whole words reversed.
Dim name As String = "i love visual basic"
Dim reversedName As String = ""
Dim tempName As String = ""
For i As Integer = 0 To name.Length - 1
If Not name.Substring(i, 1).Trim.Equals("") Then
tempName += name.Substring(i, 1)
Else
reversedName = tempName + " " + reversedName
tempName = ""
End If
Next
start from index 0 and deduct 1 from length because length count starts with one but index count starts with zero. if you put To name.Length it will return IndexOutOfBounds. Loop it from 0 To Length-1 because you need the word as is and not spelled backwards... what are placed in reverse are the words so add a temporary String variable that stores every word and add it before the saved sentence/words.
or use this
Dim strName As String() = name.Split(" ")
Array.Reverse(strName)
reversedName = String.Join(" ", strName)
This is my contribution, well as you can see its not hard to do, its really simple. There are a lot of other ways which are more short.
Console.Title = "Text Reverser"
Console.ForegroundColor = ConsoleColor.Green
'Text which will be Reversed
Dim Text As String
Console.Write("Write your text: ")
Text = Console.ReadLine
Console.Clear()
Dim RevText As String = "" '← The Text that will be reversed
Dim Index As Int32 = Text.Length '← Index used to write backwards
'Fill RevText with a char
Do Until RevText.Length = Text.Length
RevText = RevText.Insert(0, "§")
Loop
Console.WriteLine(RevText)
'Replace "Spaces" with Character, using 'Index' to know where go the chars
For Each Caracter As Char In Text
Index -= 1 'Rest 1 from the Index
RevText = RevText.Insert(Index, Caracter) '← Put next char in the reversed text
'↓ Finished reversing the text
If Index = 0 Then
RevText = RevText.Replace("§", "") 'Replace char counter to nothing
Console.WriteLine("Your text reversed: " & RevText) '← When Index its 0 then write the RevText
End If
Next
'Pause
Console.ReadKey()
I've done this project in a console, but you know, you can use this code in a normal Windows Form.
This is my first Answer in Stackoverflow :)

Locate of the string in a multi-line textbox?

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