0

I have a RichTextBox (the text where I need to find all the word corresponds to the TextBox), TextBox (for typing the word to find) and a Button, and when I click on the Button, I would like that in the RichTextBox, all the words corresponding to the word written in the TextBox are highlighted with a color (yellow for example). I know how to find the first occurrence of the word but I do not know how to find all the occurrences.

The code for highlighting only the first occurrence of the word:

'CodeCS is my RichTextBox

CodeCS.SelectionBackColor = Color.White 
CodeCS.Find(ToolStripTextBox1.Text, RichTextBoxFinds.MatchCase)
CodeCS.SelectionBackColor = Color.Yellow
4
  • It would be better if you post your attempt to solve the problem. Otherwise your question is just a classic gimme teh codez and it will not be well received
    – Steve
    Jun 17, 2017 at 20:39
  • Welcome to Stack Overflow. It would be much easier to help you if you included the code you already have written.
    – sapanoia
    Jun 17, 2017 at 20:39
  • @sapanoia CodeCS.SelectionBackColor = Color.White CodeCS.Find(ToolStripTextBox1.Text, RichTextBoxFinds.MatchCase) CodeCS.SelectionBackColor = Color.Yellow But it's highlighting only the first occurence of the word and not all the words
    – Renaud42
    Jun 17, 2017 at 20:52
  • @Steve ok sorry.
    – Renaud42
    Jun 17, 2017 at 20:55

1 Answer 1

1

Here a simple loop over the searched text (rtb is the RichTextBox to search the text for)

Sub HighlightWord(searchText As String)
    Dim len = searchText.Length
    Dim pos = rtb.Find(searchText, 0, RichTextBoxFinds.NoHighlight)
    While (pos >= 0)
        rtb.Select(pos, len)
        rtb.SelectionBackColor = Color.Yellow
        if pos + len  >= rtb.Text.Length Then
            Exit While
        End If
        pos = rtb.Find(searchText, pos + len, RichTextBoxFinds.NoHighlight)
    End While
End Sub
5
  • Converted to VB.NET
    – Steve
    Jun 17, 2017 at 21:03
  • Doesn't find restart at the top in case pos + len == length of the text in the richtextbox? What happens if you search for the last character in your example?
    – Icepickle
    Jun 18, 2017 at 1:13
  • @Icepickle yes that's correct. The Find loops back to the start of the text and never ends if your searched text happens to be the last word(char) of the RichBoxText. So a fail safe check is needed. Adding it now
    – Steve
    Jun 18, 2017 at 7:02
  • Cool, I accidentally investigated something similar yesterday and experienced the same behavior and was wondering why you didn't have that behavior :) Also, pos can be 0 i think, if it's the first character
    – Icepickle
    Jun 18, 2017 at 7:10
  • Ah, ok, not really tested it, you can see it :-)
    – Steve
    Jun 18, 2017 at 7:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.