Visual Basic: Search for and highlight text in a RichTextBox

Platform:Visual Basic
Task:Search for and highlight text in a RichTextBox
Discussion:
You need to search for and highlight text in a RichTextBox
Example:
'rtxtOutput is a richtextbox containing some text    
Private Sub HighlightText(ByVal StringToSearchFor As String)
        Dim SearchStringStart As Integer = 0
        Do While SearchStringStart <> -1
            SearchStringStart = rtxtOutput.Find(StringToSearchFor, SearchStringStart, RichTextBoxFinds.None)
            If SearchStringStart <> -1 Then
                rtxtOutput.Select(SearchStringStart, StringToSearchFor.Trim.Length)
                rtxtOutput.SelectionBackColor = Color.Red
                rtxtOutput.SelectionColor = Color.Yellow
            Else
                Exit Do
            End If
            SearchStringStart = SearchStringStart + 1
        Loop
    End Sub
Back to Index