Selecting text in vb - vb.net

I want to select a word to another word in a text box in vb.net with everything between them highlighted.
an example is
I went to the beach, had a pinic with my family and then went home at 6 o clock.
The starting word to be had and the end word being home and everything highlighted in between.
I have already used a little bit of code
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Dim a As String
Dim b As String
a = TextBox2.Text 'means what ever is in textbox2 string to the location where "a" is
b = InStr(RichTextBox1.Text, a)
If b Then
RichTextBox1.Focus()
RichTextBox1.SelectionStart = b - 1
RichTextBox1.SelectionLength = Len(a)
but its not exactly what i want it to do.
Addition to this was using RegEx Function as shown below
'gets rid of the enter line break eg <enter> command no new lines
Dim content As String = Replace(TextBox1.Text, Global.Microsoft.VisualBasic.ChrW(10), Nothing)
'searches for this tag in the brackets between ".*" will be the contents
Dim Regex As New Regex("<div.*class=""answer_text"".*id=editorText"".*""")
'Show the string
For Each M As Match In Regex.Matches(content)
'This will get the values, there are 3 atm meta.name des and content
Dim Description As String = M.Value.Split("""").GetValue(3)
'displays the content in the label
TextBox3.Text = "" & Description
Next

This will select everything between startWord and endWord excluding them both
Dim startWord As String = "had"
Dim endWord As String = "home"
Dim index As Integer = richTextBox1.Text.IndexOf(startWord)
richTextBox1.[Select](index + startWord.Length, richTextBox1.Text.IndexOf(endWord) - index - startWord.Length)

Here's a solution involving two TextBox controls:
Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Button3.Click
Dim a As String
Dim b As String
Dim index_a As Integer
Dim index_b As Integer
a = TextBox1.Text
b = TextBox2.Text
index_a = InStr(RichTextBox1.Text, a)
index_b = InStr(RichTextBox1.Text, b)
If index_a And index_b Then
RichTextBox1.Focus()
RichTextBox1.SelectionStart = index_a - 1
RichTextBox1.SelectionLength = (index_b - index_a) + Len(b)
End If
End Sub
TextBox1 contains the first word, TextBox2 contains the second word. When clicking the button, it will highlight from the first word to the end of the second word.

Related

How to find and highlight next instance of word in richtextbox in visual basic?

Here is the visual basic windows application form I am currently working on.
https://i.snag.gy/EzoXr3.jpg
How can I write code for the find next button like in this video.
https://www.dropbox.com/s/u93h9jn605uhwsu/CPT341Project2Walkthrough.avi?dl=0
If I can get a syntax to store a index variable outside the private sub of findnext button, I can solve the problem. Because everytime I click the findnext button, I have to find the respective instance of that word in the filetext. Or I can apply some code to find it in the substring of remaining text after its first occurrence.
Below is my code:
Public Class Form1
'Enter your name
'Date
'Class - CPT 341 VB.NET NJIT
Private Sub openBtn_Click(sender As Object, e As EventArgs) Handles openBtn.Click
If OpenFileDialog.ShowDialog <> Windows.Forms.DialogResult.Cancel Then
fileText.Text = My.Computer.FileSystem.ReadAllText(OpenFileDialog.FileName)
End If
End Sub
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
'Bring the form to the inital state for a different search
Dim temp As String = fileText.Text
fileText.Text = temp
outputIndex.ForeColor = Color.Black
'MessageBox to show error for empty search textbox
If inputText.Text = "" Then
MessageBox.Show("Enter Text to Search", "CPT 341 Fall 2018 - Project 2")
Else
'Declare variables
Dim txt As String : Dim x As Integer = 0 : Dim output As String
txt = inputText.Text
If fileText.Text.IndexOf(txt) <> -1 Then
Dim idx As Integer = CStr(fileText.Text.IndexOf(txt))
outputIndex.Text = idx
'Find and highlight the first word searched in the RichTextBox
fileText.Find(txt, x, fileText.TextLength, RichTextBoxFinds.None)
fileText.SelectionBackColor = Color.Yellow
'populate the string with ANSI numbers
output = Asc(txt(0))
For x = 1 To (txt.Length - 1)
output = output & " " & Asc(txt(x))
Next x
outputANSI.Text = output
ElseIf fileText.Text = "" Then
MessageBox.Show("Please open a file to search from", "CPT 341 Fall 2018 - Project 2")
Else
outputIndex.Text = txt & " is not found"
'Bring the form to inital state
fileText.Text = temp
'Change the index textbox text color to red
outputIndex.ForeColor = Color.Red
'Empty the ANSI textbox
outputANSI.Text = ""
End If
End If
End Sub
Private Sub btnFind_Click(sender As Object, e As EventArgs) Handles btnFind.Click
Dim txt As String = inputText.Text
Dim Index As Integer = fileText.Text.IndexOf(txt) + txt.Length
'Find and highlight the word searched in the RichTextBox other than first occurrence
fileText.Find(txt, Index, fileText.TextLength, RichTextBoxFinds.None)
fileText.SelectionBackColor = Color.Yellow
Index = fileText.Text.IndexOf(txt, Index) + txt.Length + 1
End Sub
Private Sub btnWords_Click(sender As Object, e As EventArgs) Handles btnWords.Click
wordCount.Text = fileText.Text.Split(" ").Length
End Sub
Private Sub btnChars_Click(sender As Object, e As EventArgs) Handles btnChars.Click
charCount.Text = fileText.Text.Length
End Sub
End Class
Or any other suggestion would be helpful.

Paste Intercept event failure

I want to intercept a paste event for a FIRST NAME textbox so that if the user pastes "Joe Smith, PhD", they will get "Joe" in the FIRST NAME textbox, and they will see "Smith, PhD" in the LAST NAME textbox. Instead, what I get is "Joe Smith,PhDJoe" in FIRST NAME textbox, and "Smith, PhD" in LAST NAME textbox. I added a messagebox as a breakpoint for me and if I uncomment that line, the msgbox displays and then the sub works perfectly. So, is this a timing issue (Windows 10/VS2015 if that matters)?
There are many posts on how to intercept paste events, and my code below is based on that. What am I doing wrong?
Public Class test
Private Sub TBfname_PASTE(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TBFname.KeyDown
Dim Pasting As String = Clipboard.GetText()
If e.Modifiers = Keys.Control AndAlso e.KeyCode = Keys.V Then
Dim SplitWhere As Int64 = 0
Dim words = Pasting.Split(" "c)
Dim firstWord = words(0)
If Pasting.Contains(" ") Then
SplitWhere = Pasting.IndexOf(" ")
Dim LN As String = ""
Dim long2 As Int64 = Pasting.Length - SplitWhere - 1
If long2 > 0 Then
LN = Pasting.Substring(SplitWhere + 1, long2)
TBLname.Text = LN
End If
' MsgBox(Pasting & " vs " & TBFname.Text)
TBFname.Text = firstWord
End If
e.Handled = True
End If
End Sub
End Class
One thing you could to is declare firstword as a Form level variable
Private firstWord As String
and then assign it in TBfname_KeyDown
firstWord = words(0)
Then in the KeyUp event re-assign TBfname.Text
Private Sub TBfname_KeyUp(sender As Object, e As KeyEventArgs) Handles TBfname.KeyUp
TBfname.Text = firstWord
End Sub

How to make a program that would detect the same characters within two strings

so i made this but when i enter a string it would only detect one character
and it wont convert the entered string to lower case too
Dim readme, readme2 As String
Dim j, i As Integer
Dim Compare As Integer
readme = TextBox1.Text
readme2 = TextBox2.Text
readme.ToLower.Substring(i, readme.Length)
readme2.ToLower.Substring(j, readme2.Length)
For i = 0 To readme.Length
For j = 0 To readme2.Length
If readme = readme2 Then
Compare = +1
End If
Next
Next
Label4.Text = Compare`enter code here`
Strings are immutable. You cannot apply a method to a string and expects that string to change in response to the inner operations of that method.
You need to reassign the result of the operation to the same string that you have used to call the method
readme = readme.ToLower()
readme2 = readme2.ToLower()
The second part of your question is more confused, are you trying to count the number of equal chars in the same position?
In that case your loop should be
Dim maxLenToCheck = Math.Min(readme.Length, readme2.Length)
For i = 0 To maxLenToCheck - 1
If readme(i) = readme2(i) Then
Compare += 1
End If
Next
In that loop you set always the Compare to 1, the correct syntax to increment the Compare variable is
Compare += 1
Following your comment below, then I presume that your loop should be written as
Dim Compare = 0
For i = 0 To readme.Length - 1
for j = 0 to readme2.Length -1
If readme(i) = readme2(j) AndAlso _
Not Char.IsWhiteSpace(readme(i)) Then
Compare += 1
End If
Next
Next
Based on the comments in the solution by Steve, the author wants to know the count of letters occurring in both strings, ignoring case and white spaces.
By my count, however, the solution should be 21, not 20. Here is a solution using LINQ that also gives visual feedback on where those letters are located:
Public Class Form1
Private Class LetterCount
Public Letter As Char
Public Count As Integer
Public Overrides Function ToString() As String
Return Letter & " : " & Count
End Function
End Class
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TextBox1.Text = "This is a Test"
TextBox2.Text = "This should be tryed before"
RichTextBox1.ReadOnly = True
RichTextBox1.Font = New Font("MS Courier", 14) ' monospaced font
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
RichTextBox1.Text = TextBox1.Text & vbCrLf & TextBox2.Text & vbCrLf
Dim charsA As New List(Of Char)(TextBox1.Text.ToLower.ToCharArray.Where(Function(x) Not Char.IsWhiteSpace(x)))
Dim charsB As New List(Of Char)(TextBox2.Text.ToLower.ToCharArray.Where(Function(x) Not Char.IsWhiteSpace(x)))
Dim DistinctCommonLetters = (From A In charsA, B In charsB Where A = B Select A).Distinct
Dim DistinctCounts =
From Letter In DistinctCommonLetters, C In charsA.Concat(charsB)
Where C = Letter
Group By Letter Into Group
Select New LetterCount With {.Letter = Letter, .Count = Group.Count}
Dim TotalMatches = DistinctCounts.Sum(Function(x) x.Count)
ListBox1.DataSource = DistinctCounts.ToList
Label1.Text = "TotalMatches: " & TotalMatches
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
Dim LC As LetterCount = ListBox1.SelectedItem
RichTextBox1.SelectAll()
RichTextBox1.SelectionColor = Color.Black
Dim index As Integer = RichTextBox1.Find(LC.Letter, 0, RichTextBoxFinds.None)
While index <> -1
RichTextBox1.Select(index, 1)
RichTextBox1.SelectionColor = Color.Red
index = RichTextBox1.Find(LC.Letter, index + 1, RichTextBoxFinds.None)
End While
End Sub
End Class

Random Letter Choosing for Textbox

So this code by Neethu Soman,
Dim input As String = TextBox2.Text '<--- this should be input "Hello I am Greg"
TextBox2.Text = "" '<--- clear the textbox to store output
Dim rnd As New Random '<---- generating new random number
For Each c As Char In input '<--- iterate through each character
If rnd.Next() Mod 2 = 0 Then
TextBox2.Text &= UCase(c) '<--- if true then print particular letter in upperCase
Else
TextBox2.Text &= LCase(c) '<--- if true then print particular letter in LowerCase
End If
Next
basically does what is supposed to, it converts random letter to lower, and upper case with a 50/50 chance. Although, that one problem is that is clears the text, and rewrites it in its new converted form, which is the problem. Is there a way to make this work without having to clear the text?
Thanks for make a try with my answer, you can convert random letter to lower, Or upper case with a 50/50 chance using the following code without using TextBox2.Text = ""
Private Sub TextBox2_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox2.KeyPress
Dim rnd As New Random'<--- Generating random number
If rnd.Next() Mod 2 = 0 Then
e.KeyChar = UCase(e.KeyChar) '<--- if true then change key char to upperCase
Else
e.KeyChar &= LCase(e.KeyChar) '<--- if true then change key char to LowerCase
End If
End Sub
If you want to do it in button click means:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim randomString As String = ""
Dim rnd As New Random
For Each c As Char In TextBox2.Text
If rnd.Next() Mod 2 = 0 Then
randomString &= UCase(c)
Else
randomString &= LCase(c)
End If
Next
TextBox2.Text = randomString
End Sub

Text file manipulation using visual basic

Hi I am looking for a way to take a text file that has 1 set of numbers per line and make a new text file that has taken the set of numbers and put them into 2 spaced out columns per line. Using Visual Basic 2010 Ex:
My First text file will look similar to this: test1.txt
12345
23456
34567
45678
56789
67890
But I would like to convert it to look like this and save it as a new file: text2.txt
12345 23456
34567 45678
56789 67890
With more spacing in between the set of numbers. I have been struggling with this for about a week now and I have put myself back at square one with it. Thank you all for your time and hope you all have a good day. Joe.
Here is my current code. I am embarrassed to say the least. I am taking an exsisting file and formatting it to have a space between each line of numbers and then reading it into a richtextbox to convert it to a barcode font then saving it. At that point I have no idea how to make the format the way I need it to be putting 2 sets of numbers on one line.
Private Sub btnLoad_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles btnLoad.Click
ListBox1.Items.AddRange(IO.File.ReadAllLines("C:\test\serintest.txt"))
End Sub
Private Sub btnConvert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles btnConvert.Click
Dim FILE_NAME As String = "C:\test\serscantemp.rtf"
Dim i As Integer
Dim t As Integer
TextBox1.Text = ListBox1.Items.Count.ToString(t)
Dim objWriter As New System.IO.StreamWriter(FILE_NAME)
For i = 0 To TextBox1.Text - 1
'objWriter.WriteLine(aryText(i))
objWriter.WriteLine(ListBox1.Items(i))
objWriter.WriteLine("")
Next
objWriter.Close()
Me.RichTextBox.LoadFile("C:\test\serscantemp.rtf", _
RichTextBoxStreamType.PlainText)
RichTextBox.SaveFile("c:\test\barcodetext.rtf", _
RichTextBoxStreamType.RichText)
End Sub
Joe,
Try this.
I am concatenating the numbers into a string variable and keeping a counter. If the counter = 2 then i write out the concatenated string to RichTextBox and clear counter and string variable
Private Sub btnConvert_Click(sender As Object, e As EventArgs) Handles btnConvert.Click
Dim FILE_NAME As String = "C:\temp\serscantemp.rtf"
Dim i As Integer
Dim t As Integer
Dim s As String
Dim c As Integer
TextBox1.Text = ListBox1.Items.Count.ToString(t)
Dim objWriter As New System.IO.StreamWriter(FILE_NAME)
c = 0
s = ""
For i = 0 To TextBox1.Text - 1
c = c + 1
If s > "" Then
s = s & " "
End If
s = s & ListBox1.Items(i)
If c = 2 Then
objWriter.WriteLine(s)
objWriter.WriteLine("")
s = ""
c = 0
End If
'objWriter.WriteLine(aryText(i))
Next
objWriter.Close()
RichTextBox1.LoadFile("C:\temp\serscantemp.rtf", _
RichTextBoxStreamType.PlainText)
RichTextBox1.SaveFile("c:\temp\barcodetext.rtf", _
RichTextBoxStreamType.RichText)
End Sub
I hope this is what you are looking for.
Here's another way to do it that you might also want to try though almost the same as Ed's answer. Just call the routine from btnConvert click event. Also make sure to include Import System.IO
Private Sub Reformat(sourceFile As String, destFile As String)
Dim arr As String() = File.ReadAllLines(sourceFile)
Dim s As String = String.Empty
Dim lst As New List(Of String)()
Dim iCtr As Integer = 0
For i As Integer = 0 To arr.Length - 1
If Not String.IsNullOrWhiteSpace(arr(i)) Then
s += arr(i) & " "
iCtr += 1
If iCtr = 2 Then
lst.Add(s.Trim())
iCtr = 0
s = String.Empty
End If
End If
Next
If Not String.IsNullOrWhiteSpace(s.Trim()) Then
lst.Add(s)
End If
File.WriteAllLines(destFile, lst.ToArray())
End Sub
By the way, this is my first post in SO. Just saying.