Ignoring the CAsE in RichTextBoxFinds
Hello Devs,
I am new to VB.net, and to this forum, so please be patient if I make any errors.
I have a problem with my code below. The RichTextBoxFinds.None doesn't seem to work.
I have a richtextbox (RichTxt_CV) and a textbox (txtFind_CV). I want the richtext box, to highlight any word in the txtfind_CV textbox, in Red.
This is almost working, but no matter what I try, I just can't get it to igore the CaSingG of the txtfind_Cv textbox. I think I have tried everything. Any suggestions?
Code:
Private Sub HighlightCVText() 'This highlights the searched for word in the CV box
If txtFind_CV.Text = "" Then GoTo endme
Dim textEnd As Integer = RichTxt_CV.TextLength
Dim Textindex As Integer = 0
Dim lstIndex As Integer = RichTxt_CV.Text.LastIndexOf(txtFind_CV.Text)
While Textindex < lstIndex
RichTxt_CV.Find(txtFind_CV.Text, Textindex, textEnd, RichTextBoxFinds.None)
RichTxt_CV.SelectionColor = Color.Red
Dim bfont As New Font(RichTxt_CV.Font, FontStyle.Bold)
RichTxt_CV.SelectionFont = bfont
Textindex = RichTxt_CV.Text.IndexOf(txtFind_CV.Text, Textindex) + 1
End While
endme:
End Sub
Thanks so much in advance for your help.
Re: Ignoring the CAsE in RichTextBoxFinds
Code:
Dim x, y As Integer
y = 0
Do
y = RichTextBox2.Text.IndexOf(TextBox1.Text, y, StringComparison.CurrentCultureIgnoreCase)
If y <> -1 Then
RichTextBox2.Select(y, TextBox1.Text.Length)
RichTextBox2.SelectionColor = Color.Red
y = y + TextBox1.Text.Length
If y + TextBox1.Text.Length >= RichTextBox2.TextLength Then Exit Do
Else
Exit Do
End If
Loop
Re: Ignoring the CAsE in RichTextBoxFinds
Thanks for your reply dbasnett
As I mentioned, I am a newbie to .Net, so I am probably not seeing something obvious, but I tried your code and it just loops continually.
I notice you don't use the x integer ... could it be something to do with this?
Thanks again for your help though.
Re: Ignoring the CAsE in RichTextBoxFinds
This solution uses regex. Surrounding the word you're search for with \b, tells the parser to match whole words only.
Code:
'Imports System.Text.RegularExpressions
Private Sub HighlightCVText(ByVal word As String)
Dim wordLength As Integer = word.Length
Dim excapedWord As String = Regex.Escape(word)
Dim rx As New Regex("\b" & excapedWord & "\b", RegexOptions.IgnoreCase)
Dim bFont As New Font(RichTxt_CV.Font, FontStyle.Bold)
For Each m As Match In rx.Matches(RichTxt_CV.Text)
Dim textIndex As Integer = m.Index
RichTxt_CV.Select(textIndex, wordLength)
RichTxt_CV.SelectionColor = Color.Red
RichTxt_CV.SelectionFont = bFont
Next
RichTxt_CV.SelectionLength = 0
End Sub
Re: Ignoring the CAsE in RichTextBoxFinds
Thanks so much Wild Bill - you are a genius.
So sorry that I am only replying now. Was busy with other parts of the project and didn't get a chance to check if anyone had replied.
This works perfectly.
For others using this code, don't forget to
dim word as string = txtFind_CV.Text
Again, Wild Bill, thanks so much.