Search code examples
c#colorstextboxsubstring

How to change the font color of some substring in the textbox in C# Winform?


If I want to upload a text file into the textbox and want to highlight certain words with a font color change, i know that i need to write TextBox.ForeColor = Color.SomeColor;
But if i want that not all the text will be in the same color, only some Substrings.
How can I do that?


Solution

  • Check the answer by Pieter Joost van de Sande.

    You can't do this in the TextBox control, only in the RichTextBox control.

    if( myRichTextBox.TextLenght >= 5 )
    {
    myRichTextBox.Select( 0, 5 );
    myRichTextBox.SelectionColor = Color.Green;
    }
    
    if( myRichTextBox.TextLenght >= 15 )
    {
    myRichTextBox.Select( 10, 15 );
    myRichTextBox.SelectionColor = Color.Red;
    }