I'm using a RichTextBox find function. It works fine until I stick it in a While loop. Then it won't do anything.
This code works:
Dim startTEXT As Integer = 0
Dim endTEXT As Integer = RichTextBox1.Text.LastIndexOf(tword)
While startTEXT < endTEXT
RichTextBox1.Find(tword, startTEXT, RichTextBox1.TextLength, RichTextBoxFinds.WholeWord)
RichTextBox1.SelectionFont = New Font(RichTextBox1.SelectionFont.FontFamily, RichTextBox1.SelectionFont.Size, FontStyle.Underline)
RichTextBox1.SelectionColor = Color.Red
startTEXT = RichTextBox1.Text.IndexOf(tword, startTEXT) + 1
End While
This code does not:
For Each tword In ListBox1.Items
Dim startTEXT As Integer = 0
Dim endTEXT As Integer = RichTextBox1.Text.LastIndexOf(tword)
While startTEXT < endTEXT
RichTextBox1.Find(tword, startTEXT, RichTextBox1.TextLength, RichTextBoxFinds.WholeWord)
RichTextBox1.SelectionFont = New Font(RichTextBox1.SelectionFont.FontFamily, RichTextBox1.SelectionFont.Size, FontStyle.Underline)
RichTextBox1.SelectionColor = Color.Red
startTEXT = RichTextBox1.Text.IndexOf(tword, startTEXT) + 1
End While
Next
What is preventing the find function from working? Using VB.NET 2010.
Option Strict On
, then declare the Font outside the loops as, e.g.,dim selFont = New Font(RichTextBox1.Font, FontStyle.Underline)
and set it either in the loop or outside the loop:RichTextBox1.SelectionFont = selFont
(since it appears the Font doesn't change, you can set it once right after you have declared it, outside the loops) -- You may want to replace this procedure with something like this: Why can't I change the color of repeated words in a RichTextBox?, it's much easier to handle (and debug).Option Strict On
. That's not really an option, it's a necessity. That option set toOFF
is meant to ease the port of VB6 app to VB.Net and exists for this reason only. In a VB.Net app, this is just trouble and trickery and source of problems hard to debug, not mentioning unexplicable run-time exceptions and misbehaviors. The fact that some people abuse it is not an excuse for anyone.\b
, as in:dim pattern = String.Concat(ListBox1.Items.Cast(Of String).Select(Function(w) "\b" & w & "\b|"))
. As you can see,RegexOptions.IgnoreCase
is already set in that code, as a Regex Option. But this can be set with a token, too. -- The method above uses LINQ'sSelect()
, which is usually imported by default. If it's not, addImports System.Linq
. But you can build thepattern
string with a standard loop instead. With a Regex, the search procedure can become very flexible.