Search code examples
vb.netcolorsrichtextboxrichtext

change the color of a line or a word in a richtextbox?


I can change the color of ONE line and/or ONE word perserving the other colors in the richtextbox?

For example i want to change the line "Processing: ..." to yellow colour, It's possible?

Thankyou for read

enter image description here


Solution

  • This hopefuly should do the trick for you, for example if the line contains "Processing..."

        for(int i=0; i<rtb.Lines.Length; i++) 
    { 
       string text = rtb.Lines[i];
       rtb.Select(rtb.GetFirstCharIndexFromLine(i), text.Length); 
       rtb.SelectionColor = colorForLine(text); 
    } 
    
    private Color colorForLine(string line)
    {
        if(line.Contains("[Processing...]", StringComparison.InvariantCultureIgnoreCase) return Color.Green;
    

    By the way I know you said this is for vb.net, but you shoudl be able to use a convertor to convert your code to vb.net Here is a link for one

    C# to VB

    I have no idea if this is correct but i think it looks a little bit like this in vb

    Private Sub Test()
        For Each i As Integer In RichTextBox1.Lines.Length
    
            Dim Text As String = RichTextBox1.Lines(i)
            RichTextBox1.Select(RichTextBox1.GetFirstCharIndexFromLine(i), Text.Length)
            RichTextBox1.SelectionColor = ColorForLine(Text)
        Next
    End Sub
    
    Private Function ColorForLine(Line As String) As color
        If Line.Contains("Processing", ) Then
            Return ColorForLine.Green
        End If
    End Function