Comparing text in two Richtextboxes and get the differences - vb.net

I'm want to compare the text between two richtextboxes and get the differences in the third one. Without highlight the text.
So far, the best option is this solution
The first solution works, but it doesn't remove the text present in richtextbox2 from the richtextbox1.
Endeed, the user asked
if they are the same do nothing.
My case is complete the opposite and still i cannot find a solution.
Thanks

First, you need to add a combobox to your form named (combobox1)
then add these items in it:
RichTextbox1 - RichTextbox2
RichTextbox2 - RichTextbox1
second, add a button named (button1), under this button click event
insert this code:
RichTextBox3.Clear()
If RichTextBox1.Text <> "" And RichTextBox2.Text <> "" And RichTextBox1.Text <> RichTextBox2.Text And ComboBox1.SelectedItem = "RichTextbox1 - RichTextbox2" Then
Dim txt1(RichTextBox1.Text.Split(" ").Length) As String
Dim txt2(RichTextBox2.Text.Split(" ").Length) As String
txt1 = RichTextBox1.Text.Split(" ")
txt2 = RichTextBox2.Text.Split(" ")
Dim diff1 As String = ""
For Each diff As String In txt1
If Array.IndexOf(txt2, diff.ToString) = -1 Then
diff1 += diff.ToString & " "
End If
Next
RichTextBox3.Text = diff1.ToString
End If
If RichTextBox1.Text <> "" And RichTextBox2.Text <> "" And RichTextBox1.Text <> RichTextBox2.Text And ComboBox1.SelectedItem = "RichTextbox2 - RichTextbox1" Then
Dim txt1(RichTextBox1.Text.Split(" ").Length) As String
Dim txt2(RichTextBox2.Text.Split(" ").Length) As String
txt1 = RichTextBox1.Text.Split(" ")
txt2 = RichTextBox2.Text.Split(" ")
Dim diff2 As String = ""
For Each diff As String In txt2
If Array.IndexOf(txt1, diff.ToString) = -1 Then
diff2 += diff.ToString & " "
End If
Next
RichTextBox3.Text = diff2.ToString
End If
now, you have 2 options:
if you choose (RichTextbox1 - RichTextbox2) from the combobox then click the button, richtextbox3 will display the text which is found in richtextbox1 and not found in richtextbox2, while if you choose (RichTextbox2 - RichTextbox1), the opposite will happen
finally, if the 2 richtextboxes is the same, nothing will occur
Also you could use String.Join *
Under Button1 click event replace this code with the previous one:
Dim intsA = RichTextBox1.Text.Split(" ")
Dim intsB = RichTextBox2.Text.Split(" ")
Dim myresult = intsA.Except(intsB).ToArray()
RichTextBox3.Text = String.Join(" ", myresult)
if you found this useful, mark it as answer

Related

Split multi line in VB

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

Repeat character in Two or More Textboxes VB Net

I want to compare the Textbox1 with TextBox2, or Textbox line 1 of the text box to the 2nd line, to show me the existing Character in another textbox, or show me how many characters are repeated. iI really like learning, so I would be helpful because I want to learn...
TextBox1.Text = 1,4,7,11,13,16,19,20,28,31,44,37,51,61,62,63,64,69,71,79,80
TextBox2.Text = 1,5,7,10,13,16,26,20,28,31,44,37,51,72,73,74,69,71,79,80
TextBox3.Text = Character Repeated: 1,7,13,16,20,28,31,44,37,51,69,71,79,80
TextBox4.Text = Number of Character Repeated = 14
TextBox5.Text = Number of Character which has not been repeated: 4,11,19,61,62,63,64 etc, you got to idea
TextBox6.Text = Number of Character isn't Repeated: 7
here are some codes: but I do not know how to apply them correctly.
Code 1: Show repetable character:
' Split string based on space
TextBox1.Text = System.IO.File.ReadAllText(Mydpi.Text)
TextBox2.Text = System.IO.File.ReadAllText(Mydpi.Text)
TextBox4.Text = System.IO.File.ReadAllText(Mydpi.Text)
For i As Integer = 0 To TextBox2.Lines.Count - 1
Dim textsrtring As String = TextBox4.Lines(i)
Dim words As String() = textsrtring.Split(New Char() {","c})
Dim found As Boolean = False
' Use For Each loop over words
Dim word As Integer
For Each word In words
TxtbValBeforeCompar.Text = TextBox1.Lines(i)
CompareNumbers()
If TextBox1.Lines(i).Contains(word) Then
found = True
Dim tempTextBox As TextBox = CType(Me.Controls("Checkertxt" & i.ToString), TextBox)
On Error Resume Next
If TextBox2.Lines(i).Contains(word) Then
If tempTextBox.Text.Contains(word) Then
Else
tempTextBox.Text = tempTextBox.Text + " " + TxtbValAfterCompar.Text()
End If
Else
End If
End If
Next
Next
Private Sub CompareNumbers()
'First Textbox that is to be used for compare
Dim textBox1Numbers As List(Of Integer) = GetNumbersFromTextLine(N1Check.Text)
'Second Textbox that is to be used for compare
Dim textBox2Numbers As List(Of Integer) = GetNumbersFromTextLine(TxtbValBeforeCompar.Text)
'Union List of Common Numbers (this uses a lambda expression, it can be done using two For Each loops instead.)
Dim commonNumbers As List(Of Integer) = textBox1Numbers.Where(Function(num) textBox2Numbers.Contains(num)).ToList()
'This is purely for testing to see if it worked you can.
Dim sb As StringBuilder = New StringBuilder()
For Each foundNum As Integer In commonNumbers
sb.Append(foundNum.ToString()).Append(" ")
TxtbValAfterCompar.Text = (sb.ToString())
Next
End Sub
Private Function GetNumbersFromTextLine(ByVal sTextLine As String) As List(Of Integer)
Dim numberList As List(Of Integer) = New List(Of Integer)()
Dim sSplitNumbers As String() = sTextLine.Split(" ")
For Each sNumber As String In sSplitNumbers
If IsNumeric(sNumber) Then
Dim iNum As Integer = CInt(sNumber)
TxtbValAfterCompar.Text = iNum
If Not numberList.Contains(iNum) Then
TxtbValAfterCompar.Text = ("")
numberList.Add(iNum)
End If
Else
End If
Next
Return numberList
End Function
Code 2: Remove Duplicate Chars (Character)
Module Module1
Function RemoveDuplicateChars(ByVal value As String) As String
' This table stores characters we have encountered.
Dim table(value.Length) As Char
Dim tableLength As Integer = 0
' This is our result.
Dim result(value.Length) As Char
Dim resultLength As Integer = 0
For i As Integer = 0 To value.Length - 1
Dim current As Char = value(i)
Dim exists As Boolean = False
' Loop over all characters in the table of encountered chars.
For y As Integer = 0 To tableLength - 1
' See if we have already encountered this character.
If current = table(y) Then
' End the loop.
exists = True
y = tableLength
End If
Next
' If we have not encountered the character, add it.
If exists = False Then
' Add character to the table of encountered characters.
table(tableLength) = current
tableLength += 1
' Add character to our result string.
result(resultLength) = current
resultLength += 1
End If
Next
' Return the unique character string.
Return New String(result, 0, resultLength)
End Function
Sub Main()
' Test the method we wrote.
Dim test As String = "having a good day"
Dim result As String = RemoveDuplicateChars(test)
Console.WriteLine(result)
test = "areopagitica"
result = RemoveDuplicateChars(test)
Console.WriteLine(result)
End Sub
End Module
You could make use of some LINQ such as Intersect and Union.
Assuming your TextBox1 and TextBox2 contains the text you have provided.
Here's a simple method to find repeated and non repeated characters.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim firstBoxList = TextBox1.Text.Split(",").ToList()
Dim secondBoxList = TextBox2.Text.Split(",").ToList()
Dim intersectionList = firstBoxList.Intersect(secondBoxList)
For Each str As String In intersectionList
TextBox3.Text = TextBox3.Text & str & ","
Next
TextBox4.Text = intersectionList.Count()
Dim notRepeatedCharacter = firstBoxList.Union(secondBoxList).ToList
notRepeatedCharacter.RemoveAll(Function(x) intersectionList.Contains(x))
For each str As String In notRepeatedCharacter
TextBox5.Text = TextBox5.Text & str & ","
Next
TextBox6.Text = notRepeatedCharacter.Count()
End Sub
The output is something like that:
This consider both of the textboxes not repeated character.
If you just want to find the not repeated characters from first list to the second, this should do it:
firstBoxList.RemoveAll(Function(x) secondBoxList.Contains(x))
For Each str As String In firstBoxList
TextBox7.Text = TextBox7.Text & str & ","
Next
TextBox8.Text = firstBoxList.Count
And this is the output:
Here's the full code using String.Join to make the lists look smoother in the text boxes:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'First we grab all the numbers written inside the textboxes (I am not verifying anything)
Dim firstBoxList = TextBox1.Text.Split(",").ToList()
Dim secondBoxList = TextBox2.Text.Split(",").ToList()
'Second we intersect the two lists and show them
Dim intersectionList = firstBoxList.Intersect(secondBoxList)
TextBox3.Text = String.Join(",", intersectionList)
TextBox4.Text = intersectionList.Count()
'We're checking the distintc character from both lists
Dim notRepeatedCharacter = firstBoxList.Union(secondBoxList).ToList
notRepeatedCharacter.RemoveAll(Function(x) intersectionList.Contains(x))
TextBox5.Text = String.Join(",", notRepeatedCharacter)
TextBox6.Text = notRepeatedCharacter.Count()
'we're checkng the distinct character inside first list that doesn't show in second list
firstBoxList.RemoveAll(Function(x) secondBoxList.Contains(x))
TextBox7.Text = String.Join(",", firstBoxList)
TextBox8.Text = firstBoxList.Count
End Sub

I want to output specific line from text file but I don't know how

So basically I'm making a library book record thing that tracks new books,view title and author.Right now, I'm in the stage of viewing all title and author in alphabetical order and I made them stored in a text file. My teacher suggested me to use bubble sort for sorting in alphabetical but right now I need more indepth explanation. Please help a man out thanks :D
Oh and the text file goes like this(no space in between except the last one using &vbcrlf):
Title
Author
Date published
Pagenum
ISBN
Sub Main()
'Making a book using the attributes and methods
Dim title As String = ""
Dim datepublished As Date = #01/01/0001# ' date is in month/day/year
Dim pagenum As Integer = 0
Dim isbn As String = ""
Dim author As String = ""
Dim amountbooks As Integer = 0
Dim choice As String = ""
'Declaring an object variable 'filename' which shows the file name (bookrecords.txt) and the path given
Dim filename As String = "C:\Users\Local_PC\Desktop\Try_oop_book\bookrecords.txt"
'Making a menu for the client
' A While loop for the menu that checks the user's input
While choice <> "1" AndAlso choice <> "2" AndAlso choice <> "3" AndAlso choice <> "4"
Console.Clear()
Console.WriteLine("----------LIBRARY MENU----------")
Console.WriteLine("[ 1 ]" & "Add New Book(s)")
Console.WriteLine("[ 2 ]" & "View all Book Titles")
Console.WriteLine("[ 3 ]" & "View all Authors")
Console.WriteLine("[ 4 ]" & "Exit")
Console.WriteLine(" ")
Console.Write("Pick a Menu Number: ")
choice = Console.ReadLine()
If choice <> "1" And choice <> "2" And choice <> "3" And choice <> "4" Then
Console.WriteLine("Please type in a valid input next time, press enter to retry again.")
Console.ReadLine()
Else
'Using choice, it goes to check which menu the user typed in.
If choice = "1" Then
'The user has chosen 1 which is to add new book(s) to the menu system.
'Setting the title of the book using mybook.setTitle
Console.WriteLine("How many books do you want to add?")
amountbooks = Console.ReadLine()
Dim bookarr(amountbooks) As Book 'This will initialise after amountbooks has been entered. Prevents from getting invalid index number of 0.
For x = 1 To amountbooks ' This loop will go over how many amount of books the user wants to add in to.
bookarr(x) = New Book()
Console.WriteLine("What is the title of the book?")
title = Console.ReadLine() 'This gives the value to store inside the variable 'title'
bookarr(x).setTitle(title) 'This line will set that 'title' into array bookarr
Console.WriteLine("Who is the author of the book?")
author = Console.ReadLine()
bookarr(x).setAuthor(author)
Console.WriteLine("When is the book published?")
datepublished = Console.ReadLine()
bookarr(x).setDatePublished(datepublished)
Console.WriteLine("How many page numbers are there?")
pagenum = Console.ReadLine()
bookarr(x).setPageNum(pagenum)
Console.WriteLine("What is the ISBN(code) of the book?")
isbn = Console.ReadLine()
bookarr(x).setISBN(isbn)
Console.Clear() 'clears everything after it has been written into a file
If System.IO.File.Exists(filename) = True Then
' Setting up an object variable for the streamwriter (which is the path folder and its name).
Dim objwriter As New System.IO.StreamWriter(filename, True) ' Has been set to true because the file exists and this will append(ADD) for the next str.
' if a file doesn't exists, it should be false which will ensure that a text file is created first.
objwriter.WriteLine(bookarr(x).getTitle & vbCrLf & bookarr(x).getAuthor & vbCrLf & bookarr(x).getDatePublished & vbCrLf & bookarr(x).getPageNum & vbCrLf & bookarr(x).getISBN & vbCrLf)
objwriter.Close() ' Closes the pathway to filename.
MsgBox("TEXT HAS BEEN SUCCESSFULLY REGISTERED")
Else
MsgBox("FILE DOES NOT EXIST")
End If
Next x
Else
If choice = "2" Then 'View all book titles
Dim readall As String = ""
Dim readtitle As String = ""
If System.IO.File.Exists(filename) = True Then
Dim objreader As New System.IO.StreamReader(filename)
readtitle = objreader.ReadLine
objreader.Close() 'Closes the pathway to filename
Console.WriteLine(readtitle) 'Outputs the all book title in alphabetical
Else
MsgBox("FILE DOES NOT EXIST")
End If
Console.ReadLine()
Else
If choice = "3" Then
Dim readauthor As String
Dim amountauthor As Integer = 0
Dim objreader As New System.IO.StreamReader(filename)
Else
Environment.Exit(0) 'idk I found this online :P but it works for exiting the console
End If
Console.ReadLine()
End If
End If
End If
End While
End Sub

Listbox1 add all the items to richtextbox in the same format

I'm trying to get all the ListBox1 items and have them go to the RichTextBox1. I want it in the same format that it's in the ListBox1. I've tried different code and they seem to give extra blank lines in between items. So far I've thought of this but it give extra blank lines.
Dim counter As String
counter = ListBox1.Items.Count - 1
ListBox1.SelectedIndex = 0
If ListBox1.SelectedIndex = 0 Then
Do Until ListBox1.SelectedIndex = counter
ListBox1.SelectedIndex = ListBox1.SelectedIndex + 1
RichTextBox1.Text = RichTextBox1.Text & vbNewLine & ListBox1.SelectedItem
Loop
End If
Use LINQ to select all the items and join on Environment.NewLine:
.Net >= 4.0
Me.RichTextBox1.Text = String.Join(Environment.NewLine, (From item As Object In Me.ListBox1.Items Select Me.ListBox1.GetItemText(item).Trim()))
.Net >= 3.5
Me.RichTextBox1.Text = String.Join(Environment.NewLine, (From item As Object In Me.ListBox1.Items Select Me.ListBox1.GetItemText(item).Trim()).ToArray())
you are adding a vbNewLine before you add the ListBox text... you should put that at the end of the line RichTextBox1.Text = RichTextBox1.Text & ListBox1.SelectedItem & vbNewLine and you also shouldn't increment your selected index value until after you add the line...
Alternatively, You can do this..
For i = 0 To ListBox1.Items.Count - 1
RichTextBox1.Text = RichTextBox1.Text & ListBox1.Items(i) & vbCrLf
Next
OR this SO question has a few good examples using LINQ and condensed query code...
passing all the items of listbox in the richtextbox
This is because initially the richtextbox is empty. Hence RichTextBox1.Text = RichTextBox1.Text & vbNewLine & ListBox1.SelectedItem will add a New Line first and the add the second element of list to the richtextbox, this is because you incremented the selected index value by 1 before adding to the richtexbox. So your code can be used in an effective way as follows:
Dim counter As Integer = ListBox1.Items.Count - 1
ListBox1.SelectedIndex = 0
If ListBox1.SelectedIndex = 0 Then
Do Until ListBox1.SelectedIndex = counter
RichTextBox1.Text = RichTextBox1.Text & ListBox1.SelectedItem & vbNewLine
ListBox1.SelectedIndex = ListBox1.SelectedIndex + 1
Loop
End If
try saving the listbox to a file using a streamwriter and writeline(), then opening it into a text box using streamreader and readtoend()
'assuming you have the default names
dim reader As streamreader, writer As streamwriter
writer = new streamwriter("TMP")
for each x as object in listbox1.items
writer.writeline(X)
next
writer.close()
reader=new streamreader("TMP")
textbox1.text=reader.readtoend()
reader.close()

Highlight text in a richtextbox in windows forms

How to make when i type in a RichTextBox a certain word it gets highlited?
how do i find words in the text to use SelectionColor or SelectionFont
For example: i want that all times that the word "hello" appear in the RichTextBox it turn to bold or turn into a color...
Then if i open my program and type "hello, how are you?" the word hello turns into bold... any idea? (my idea is to make a text editor with syntax highlight that ill specify the words)
(sorry if there is another question like that, i tried to search but i didn't find a answer that helped me)
its windows forms, visual basic
This code should do the work:
Dim searchstring As String = "hello"
' The word you're looking for
Dim count As New List(Of Integer)()
For i As Integer = 0 To richTextBox1.Text.Length - 1
If richTextBox1.Text.IndexOf(searchstring, i) <> -1 Then
'If the word is found
'Add the index to the list
count.Add(richTextBox1.Text.IndexOf(searchstring, i))
End If
Next
Try
For i As Integer = 0 To count.Count - 1
richTextBox1.[Select](count(i), searchstring.Length)
richTextBox1.SelectionFont = New Font(richTextBox1.Font, FontStyle.Bold)
count.RemoveAt(i)
Next
Catch
End Try
richTextBox1.[Select](richTextBox1.Text.Length, 0)
richTextBox1.SelectionFont = New Font(richTextBox1.Font, FontStyle.Regula
For each index select the text and make it bold.
Now add this code to the TextChanged-Event to check any time the text changed for your word.
I got it in a different way:
While Not RichTextBox1.Text.IndexOf("hello", startIndex) = -1
selectedIndex= RichTextBox1.SelectionStart
Try
RichTextBox1.Select(RichTextBox1.Text.IndexOf("test", startIndex) - 1, 1)
Catch
End Try
If RichTextBox1.SelectedText = " " Or RichTextBox1.SelectedText = Nothing Then
RichTextBox1.Select(RichTextBox1.Text.IndexOf("hello", startIndex) + "test".Length, 1)
If RichTextBox1.SelectedText = " " Or RichTextBox1.SelectedText = Nothing Then
RichTextBox1.Select(RichTextBox1.Text.IndexOf("hello", startIndex), "test".Length)
RichTextBox1.SelectionColor = Color.Blue
End If
End If
startIndex = RichTextBox1.Text.IndexOf("hello", startIndex) + "hello".Length
RichTextBox1.SelectionStart = selectedIndex
RichTextBox1.SelectionLength = 0
RichTextBox1.SelectionColor = Color.Black
End While
I don't know if it is the best way, but works.
That is a code for highlighting selected text at yellow (can be replaced by any other color), after finding it:
'find the text that need to be highlighted.
foundIndex = RichTextBox1.Find("hello", foundIndex + 1, -1, selectedFinds)
RichTextBox1.Focus()
If foundIndex = -1 Then
MessageBox.Show("This document don't contains the text you typed, or any of the text you typed as a whole word or mach case.", "Find Text Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
else
'now the text will be highlighted.
RichTextBox1.SelectionBackColor = Color.Yellow
Richtextbox1.focus
End If
I hope that code will help.
Private Sub RichTextBox1_DragOver(sender As Object, e As DragEventArgs) Handles RichTextBox1.DragOver
Dim p As Point
p.X = e.X
p.Y = e.Y
Dim num As Integer
Dim rightTXT As String
Dim leftTXT As String
Dim textpart As String
Dim TSelect As Boolean
Dim curpos As Integer = RichTextBox1.GetCharIndexFromPosition(RichTextBox1.PointToClient(p))
Dim PosStart As Integer
TSelect = False
If e.Data.GetDataPresent(DataFormats.StringFormat) Then
e.Effect = DragDropEffects.All
Try
leftTXT = Microsoft.VisualBasic.Left(RichTextBox1.Text, curpos)
If InStr(leftTXT, "%", CompareMethod.Text) Then
rightTXT = Microsoft.VisualBasic.Right(RichTextBox1.Text, Len(RichTextBox1.Text) - curpos)
If InStr(rightTXT, "%", CompareMethod.Text) Then
PosStart = curpos - InStr(StrReverse(leftTXT), "%") + 1
num = curpos + InStr(rightTXT, "%") - PosStart - 1
textpart = (RichTextBox1.Text.Substring(PosStart, num).TrimEnd)
Label3.Text = "mouse drag over:" + textpart
Label5.Text = num.ToString()
If ListBox1.Items.Contains(textpart) Then
TSelect = True
End If
End If
End If
Catch ex As Exception
Label4.Text = ex.ToString()
End Try
End If
If TSelect Then
Me.RichTextBox1.Select(PosStart - 1, num + 2)
wordSearch = RichTextBox1.SelectedText
Label4.Text = "word drag state: true"
match = True
Else
Label3.Text = "mouse drag over:"
Label4.Text = "word drag state: false"
Me.RichTextBox1.Select(0, 0)
End If
End Sub
I find the above codes to be too lengthy/complicated for a simple task...
Dim c As Integer = 0
Dim o As Integer = 0
Dim s As Integer = 0
Dim txt As String = RTB.Text
RTB.BackColor = Color.Black
Dim starts As Integer = 0
Do While txt.Contains(key) ' this avoids unnecessary loops
s = txt.IndexOf(key)
starts = s + o
RTB.Select(starts, key.Length)
RTB.SelectionBackColor = Color.Yellow
RTB.SelectionColor = Color.Blue
txt = txt.Substring(s + key.Length)
o += (s + key.Length)
c += 1
Loop
Me.Status.Text = c.ToString() & " found" ' and the number found