Search and Highlight Text in a RichTextBox

Polas5

Member
Joined
Jul 23, 2011
Messages
14
Location
Alytus, Lithuania
Programming Experience
Beginner
How to search from textbox when you type something not form string everytime ?

Here is the code.

VB.NET:
Dim searchword As String = "i do not like this using better from textbox1.text if someone knows how to change it"

Private Sub RichTextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RichTextBox1.TextChanged
 Dim SelStart As Integer = RichTextBox1.SelectionStart
        Dim count As Integer = 0

        Dim srchMode As RichTextBoxFinds

        srchMode = RichTextBoxFinds.WholeWord

        Dim wordAt As Integer = 0

        Do While wordAt <> -1

            wordAt = RichTextBox1.Find(searchword, wordAt, srchMode)

            If wordAt = -1 Then

                Exit Do

            Else

                HightlightLine(wordAt)

                'RichTextBox1.Select(wordAt, searchword.Length)

                'RichTextBox1.SelectionBackColor = Color.Yellow

                wordAt += 1

                count += 1

            End If

        Loop

        RichTextBox1.SelectionStart = SelStart

        RichTextBox1.SelectionLength = 0

        RichTextBox1.SelectionBackColor = Color.White
    End Sub

    Private Sub HightlightLine(ByVal wordat As Integer)

        Dim lineindex As Integer = Me.RichTextBox1.GetLineFromCharIndex(wordat)

        Dim first As Integer = Me.RichTextBox1.GetFirstCharIndexFromLine(lineindex)

        Dim last As Integer = Me.RichTextBox1.GetFirstCharIndexFromLine(lineindex + 1)

        If last = -1 Then last = Me.RichTextBox1.TextLength

        Me.RichTextBox1.Select(first, last - first)

        Me.RichTextBox1.SelectionBackColor = Color.Wheat
    End Sub
 
Back
Top