Highlight words in richtextbox

poe

Member
Joined
Oct 8, 2006
Messages
12
Programming Experience
Beginner
Hello, I have a rich text box with some text in it.

I would like to highlight "the next" word when i click a button.

Say that my text is this:
Once upon a time

Then when i click the button i want "Once" to get highlighted. Then when i click the button again, i want "upon" to get highlighted, and then the next word and the next word.

Is this possible?
Thanks. :D
 
Try this:
VB.NET:
    Dim word, index As Integer
 
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles Button1.Click
        RichTextBox1.HideSelection = False
        Dim text As String = RichTextBox1.Text.Replace(vbLf, " ")
        Dim words() As String = text[SIZE=2].Split([/SIZE][SIZE=2][COLOR=#a31515]" "[/COLOR][/SIZE][SIZE=2].ToCharArray, StringSplitOptions.RemoveEmptyEntries)[/SIZE]
        If word >= words.Length Then
            word = 0
            index = 0
        End If
        index = RichTextBox1.Find(words(word), index, RichTextBoxFinds.None)
        RichTextBox1.Select(index, words(word).Length)
        index += words(word).Length
        word += 1
    End Sub
 
Last edited:
Thanks for your reply!

It works until it tries to highlight the last word on the row. Then it crashes and gives:
InvalidArgument=Value of '-1' is not valid for 'start'.

on this line:
VB.NET:
RichTextBox1.Select(index, words(word).Length)
I think it has something to do that there isnt a space after the last word, so the last word gets connected to the first word on the next row.
 
It happened because you had an extra space after the text. I modified the code to handle this, now it also handle possible other occurences of multiple spaces in text.
 
Thanks again for your reply. I tried the code but I still get that error.
It crashes on the last word on the row.

The text is on multiple rows. :/
 
Last edited:
Yes, I guess it is very natural with linebreaks in a RichTexBox, however it is very easy to fix, just remove the linebreaks from the text before breaking up the words. The original code is modified to handle also linebreaks now.
 
Back
Top