simple text color in rich text box
Solution 1
Select the text after you put it in and then change the color.
For example:
richTextBox1.Text += "Test"
richTextBox1.Select(richTextBox1.TextLength - 4, 4)
richTextBox1.SelectionColor = Color.Red
Solution 2
This code adds text "Hello" in red color and "World" in green to the RichTextBox.
RichTextBox1.SelectionColor = Color.Red
RichTextBox1.SelectedText = "Hello "
RichTextBox1.SelectionColor = Color.Green
RichTextBox1.SelectedText = "World"
Solution 3
Ive worked with it in VB6 and i think its the same: You must select the text and then apply
this.richTextBox1.SelectionColor = Color.Red
The added text always appears in the defaut color, you must select it and then change its color:
this.richTextBox1.text="Hello world!"
this.richTextBox1.selstart=0
this.richTextBox1.sellength=5
this.richTextBox1.SelectionColor = Color.Red
As i dont use vb.net, you must check the spelling but i think thats the key. The code i wrote is supposed to print "Hello" in red and "World!" in black.
Solution 4
Try this
RichTextBox2.SelectionLength = 0
RichTextBox1.SelectionStart = 0
' We deselect everything first in case the user has something selected.
RichTextBox1.SelectionColor = Color.Red
RichTextBox1.SelectedText = "Hello "
RichTextBox1.SelectionColor = Color.Green
RichTextBox1.SelectedText = "World "
This will add it to the start of the textbox. I think you could also make SelectionStart = RichTextBox1.TextLength which would put it at the end instead of the start.
Comments
-
The Digital Ninja over 2 years
I can find a million examples of doing reg ex to apply syntax highlighting to a rich text box. but what i need it just a simple way to add in a word of a diffrent color.
What would the code be to just put the words "Hello World" into a textbox and have Hello be red and World be green?
This code doesnt work.
this.richTextBox1.SelectionColor = Color.Red this.richTextBox1.text += "Test"
-
Barracuda about 12 yearsYour answer is a lot more straightforward than any of the answers, and it works for me! Thanks Meta-Knight.
-
Roni Tovi about 9 yearsThis isn't the right way to append a text to any Form control. Each time you are resetting the whole text inside a control which can be very slow when the content gets bigger and bigger. Poor coding.