Search code examples
vb.nettextbox

Find all text in textbox and change fore color only for specific string. Vb.net


What im trying to do is search specific string in textbox and change fore color with red color, and it works so far:

    Private Sub RichTextBox1_TextChanged(sender As Object, e As EventArgs) Handles RichTextBox1.TextChanged

    Dim loc As Integer
    'check if it contains the <html> tag and if it does select it and change the colour to red.
    If RichTextBox1.Text.Contains("Card Locked") Then

        loc = RichTextBox1.Find("Card Locked")
        RichTextBox1.Select(loc, 12)
        RichTextBox1.SelectionColor = System.Drawing.Color.Red
        'TextBox1.ForeColor = System.Drawing.Color.Red

    End If
    If RichTextBox1.Text.Contains("Card Unlocked") Then
        loc = TextBox1.Find("Card Unlocked")
        RichTextBox1.Select(loc, 14)
        RichTextBox1.SelectionColor = System.Drawing.Color.Red


    End If 
    End sub

But it changes color only for first serach for exmaple if in richtextbox1 i have two lines with "Card Locked" in diffrent places, it will colored only first one and another one will stay with default color. How to make it search in whole text and chage fore color everytime app founds needed string?


Solution

  • Well, i made this, if someoone will need it:

           Dim index As Integer = 0
        While index < TextBox1.Text.LastIndexOf("Card Locked")
            TextBox1.Find("Card Locked", index, TextBox1.TextLength, RichTextBoxFinds.None)
            TextBox1.SelectionColor = System.Drawing.Color.Red
            index = TextBox1.Text.IndexOf("Card Locked", index) + 1
        End While