Changing color in richtextbox multiple times goes wrong

K

Klaasjan

Hi,

In my programm users can enter text which is added to a richtextbox.
Everytime a text is added, this text had get his own color.
The first 2 times it goes fine,
eg.

hallo (red)
hallo (yellow)


But when a third time a text is added with e.g. the color blue, the
first 2 gets the color red ??
Help what am i doing wrong
Here my piece of code:

Dim c As Color

If rbtrood.Checked Then
c = Color.Red
End If

If rbtgeel.Checked Then
c = Color.Yellow
End If

If rbtblauw.Checked Then
c = Color.Blue
End If

With rtb
.Text &= rtbinvoer.Text
.SelectionStart = L
.SelectionLength = rtbinvoer.Text.Length
.SelectionColor = c
End With

L = rtb.Text.Length

Hope anyone can help me,

Thank already

Klaasjan
 
L

Larry Lard

Klaasjan said:
Hi,

In my programm users can enter text which is added to a richtextbox.
Everytime a text is added, this text had get his own color.
The first 2 times it goes fine,
eg.

hallo (red)
hallo (yellow)


But when a third time a text is added with e.g. the color blue, the
first 2 gets the color red ??
Help what am i doing wrong
Here my piece of code:
[snip]

With rtb
.Text &= rtbinvoer.Text

This is where the problem lies, my experiments have discovered. It
appears that you should never assign directly to the .Text property of
a RichTextBox - doing so erases ALL formatting information. Even this:

RichTextBox1.Text = RichTextBox1.Text

which looks like it will do nothing, actually has the side effect of
erasing ALL formatting information. Some might call this a bug, but not
me :)

In this particular instance the solution is easy: instead of
.Text &= rtbinvoer.Text

just do

.AppendText(rtbinvoer.Text)

and you get your desired result. If you need to do more complex stuff,
eg adding text to somewhere other than the end of the existing text, I
recommend this thread:

<http://groups-beta.google.com/group...nguages.vb/browse_frm/thread/22b088acbf67034e>

and a bit of experimentation.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top