Reputation: 29
Hello everyone and thanks in advance,
I have a textbox in which some text is being generated. While it's being generated I want to color the word "successfully" with Green and the word "failed" with Red.
I'm using this :
FormtxtBox.Find()("successfully")
FormtxtBox.SelectionColor = Color.YellowGreen
FormtxtBox.SelectionFont = New Font(FormtxtBox.Font.FontFamily, FormtxtBox.Font.Size, FontStyle.Bold)
FormtxtBox.DeselectAll()
FormtxtBox.Find("failed")
FormtxtBox.SelectionColor = Color.Red
FormtxtBox.SelectionFont = New Font(FormtxtBox.Font.FontFamily, FormtxtBox.Font.Size, FontStyle.Bold)
FormtxtBox.DeselectAll()
It's working but the problem I have with it is that it only colours the first "Successfully" or "Failed" string, whereas the textbox has many copies of that word in it. How can I make it color every copy of these words ?
Upvotes: 0
Views: 1037
Reputation: 700
Yep, what Guil said, .Find only finds the first occurrance.
https://msdn.microsoft.com/en-us/library/hfcsf75k(v=vs.110).aspx
I did find this article and modified it slightly:
https://support.microsoft.com/en-us/kb/176643
It recursively searches the RichTextBox, selects the searched for text, and changes the text as specified. You'd need to add an additional parameter for your font if you're changing that as well.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
FindIt(Me.RichTextBox1, "failed", Color.Red)
End Sub
Private Function FindIt(ByRef Box As RichTextBox, ByVal Search As String, ByVal Color As Color, Optional Start As Int32 = 0) As Int32
Dim retval As Int32 'Instr returns a long
Dim Source As String 'variable used in Instr
Try
Source = Box.Text 'put the text to search into the variable
retval = Source.IndexOf(Search, Start) 'do the first search,
'starting at the beginning
'of the text
If retval <> -1 Then 'there is at least one more occurrence of
'the string
'the RichTextBox doesn't support multiple active selections, so
'this section marks the occurrences of the search string by
'making them Bold and Red
With Box
.SelectionStart = retval
.SelectionLength = Search.Length
.SelectionColor = Color
.DeselectAll() 'this line removes the selection highlight
End With
Start = retval + Search.Length 'move the starting point past the
'first occurrence
'FindIt calls itself with new arguments
'this is what makes it Recursive
FindIt = 1 + FindIt(Box, Search, Color, Start)
End If
Catch ex As Exception
Debug.WriteLine(ex.Message)
End Try
Return retval
End Function
Upvotes: 1