Showing the difference between two RichTextBox controls - vb.net

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

Related

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

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

VB specific line of text to bold in a multi-line TextBox

I'm writing a reminder program in vb.net that reads a text file and displays dated entries from today to 14 days from today. I want entries for today's date to be in bold. If it makes any difference I'm using a TextBox instead of Rich TextBox This is what I've tried:
Public Sub getReadFile()
' rtfRead is the name of the TextBox
rtfRead.Text = Nothing
' Today, the first read line date
Dim startDate As Date = Date.Now()
' First dated line to read
Dim todayDate As String = (GetDateInMyFormat(startDate))
' The last read line date
Dim endDate As String = (GetDateInMyFormat(DateAdd("d", 14, startDate)))
' The first 4 characters of a line. Are the 4 charcters numbers, i.e. yyyy
Dim lineStart As Object
' The date at the beginnig of a an entry
Dim lineDate As String = Nothing
' Are the first 4 charcters of a line numeric = True
Dim isNum As Boolean = False
' TM_Notes.txt
Dim readFile As String = Nothing
Dim oldFont As Font = rtfRead.Font
Dim boldFont As Font = New Font(rtfRead.Font, FontStyle.Bold)
Try
' Create an instance of StreamReader to read from a file.
' The using statement also closes the StreamReader.
Using sr As New StreamReader("TM_Notes.txt")
Dim lineRead As String
' Read and display lines from the file until the end of
' the file is reached.
Do
lineRead = sr.ReadLine()
lineStart = Mid(lineRead, 1, 4)
isNum = IsNumeric(lineStart)
If isNum = True Then
lineDate = GetDateInMyFormat(Mid(lineRead, 1, 10))
End If
If lineDate = todayDate Then
rtfRead.Font = boldFont
Else
rtfRead.Font = oldFont
End If
If Not (lineRead Is Nothing) And isNum = False And lineDate <= endDate Then
readFile = readFile + lineRead & vbCrLf
ElseIf lineDate >= todayDate And lineDate <= endDate Then
readFile = readFile + lineRead & vbCrLf
End If
Loop Until lineRead Is Nothing
End Using
rtfRead.Text = readFile
Catch ex As Exception
' Let the user know what went wrong.
Console.WriteLine("The file could not be read:")
Console.WriteLine(ex.Message)
End Try
End Sub
I don't get any errors but today's date isn't in bold.
It today is 02-11 then the Test string line should be bold.
2014-02-11: Test string
2014-02-12: Test string 2
UPDATE
I've changed to a Rich TextBox and updated my code sample to to reflect my code changes. I'm still not getting Bold
Here's the function... You pass the text you want to find and the format (bold or italic - 1 or 2). This works really good; you can also expand this to add color if you choose. I hope you find this useful, happy coding!
'Pass in a 1 or 2; one is bold the other is italic'
Private Function FormatText(ByVal TextToFormat As String, ByVal TextFormat As Integer)
Dim count As New List(Of Integer)()
For i As Integer = 0 To rText.Text.Length - 1
If rText.Text.IndexOf(TextToFormat, i) <> -1 Then
'If the word is found add the index to the list
count.Add(rText.Text.IndexOf(TextToFormat, i))
End If
Next
Try
For i As Integer = 0 To count.Count - 1
rText.[Select](count(i), TextToFormat.Length)
Select Case TextFormat
Case 1
rText.SelectionFont = New Font(rText.Font.FontFamily, rText.Font.Size, FontStyle.Bold)
Case 2
rText.SelectionFont = New Font(rText.Font.FontFamily, rText.Font.Size, FontStyle.Italic)
End Select
count.RemoveAt(i)
Next
Catch
End Try
Return Nothing
End Function

Issue with checkbox and textbox

I'm having a little issue with my code not displaying correctly. Right now if there's text in the textbox and I select something from the checkbox list, what I selected from the checkboxlist overrides what's in the textbox. I want to keep what's in the textbox and just keep adding on what's selected.
For example: Honda's in the textbox ... I select Dodge and Mazda I want to show
Honda, Dodge, Mazda
Dim i As Integer = 0
Dim strText As String = ""
For i = 0 To cbCars.Items.Count - 1
If cbCars.Items(i).Selected Then
If strText = "" Or strTeethText = Nothing Then
strText += cbTeeth.Items(i).Text
Else
strText += ", " & cbCars.Items(i).Text
End If
End If
Next
txtCars.Text = strText.ToString()
Try
txtCars.Text += strText;
or
txtCars.AppendText(strText);
Change
Dim strText As String = ""
to
Dim strText As String = txtCars.Text
You forgot to initialize your string to the value of the textbox, which is why the textbox was getting overwritten on your click handler.

VBA - Check if ContentControl text contains formatting?

So this is what I want to do, if it's possible.
I've got a lot of rich textboxes in a Word template. And I want to create a macro that basically checks if any characters in the text entered into the placeholder is formatted with superscript, subscript, bold or underline etc.
So, What I've got so far is this
Dim i As Long
Dim txtboxString as String
For i = 1 To ActiveDocument.ContentControls.Count
If ActiveDocument.ContentControls(i).Title = "Repporttitle" Or ActiveDocument.ContentControls(i).Title = "Subtitle" Then
If ActiveDocument.ContentControls(i).LockContentControl = True Then
ActiveDocument.ContentControls(i).LockContentControl = False
End If
txtboxString = ActiveDocument.ContentControls(i).Range.Text
End If
Next i
So, now, txtboxString contains the text that was typed into the placeholder. But I want to check each letter for it's formatting. The method above only gives me the text as a simple text string. I've seen that I can check each letter of the string this way:
Dim counter as integer
Dim contentText as string '(this is passed on via the above txtboxString)
Dim letter as string
For counter = 1 To Len(contentText)
letter = Mid(contentText, counter, 1)
Next
But, this won't give me the formatting of each letter. How can I do that?
Use Characters and Font instead of Text. Like this:
Sub GetCharacterFormatting()
Dim i As Long
Dim txtboxString As Characters ''# <- this was changed from "String" to "Characters"
Dim Bold As String
Dim Italic As String
Dim Subscript As String
Dim CharacterFont As Font
Dim ap As Document: Set ap = ActiveDocument
For i = 1 To ap.ContentControls.Count
If ap.ContentControls(i).Title = "Repporttitle" Or ap.ContentControls(i).Title = "Subtitle" Then
If ap.ContentControls(i).LockContentControl = True Then
ap.ContentControls(i).LockContentControl = False
End If
txtboxString = ap.ContentControls(i).Range.Characters ''# <- this was changed from "Text" to "Characters"
Dim counter As Integer
For counter = 1 To txtboxString.Count
Index = counter
CharacterText = txtboxString(i).Text
CharacterFont = txtboxString(i).Font
''# You can just grab all the formatting for the character or use If/Then statements
Bold = "Bold: " & CharacterFont.Bold & ", "
Italic = "Italic: " & CharacterFont.Italic & ", "
Subscript = "Subscript: " & CharacterFont.Subscript & " "
''#
Next
Debug.Print Index & " (" & CharacterText & ") : " & Bold; Italic; Subscript
End If
Next i
End Sub