RichTextBox.selection.color

  • Thread starter Thread starter DG
  • Start date Start date
D

DG

i do:

for(int i=0; i<10; i++)
{
txtLog.Text = i.ToString() + "\r\n" + txtLog.Text;
startSelection = txtLog.SelectionStart;
lenghtSelection = txtLog.SelectionLength;
txtLog.Select(0, i.ToString().Length);

if(i%2 == 0)
{
txtLog.SelectionColor = Color.Black;
MessageBox.Show("");
}
else
{
txtLog.SelectionColor = Color.Red;
MessageBox.Show("");
}
txtLog.Select(startSelection, lenghtSelection);

}

i expect every other row to be different color but
first row get colored well, but afer new row is colored in new color, all
rows under are colored to old color

e.g:

(5th step)
black
red
red
red
red

(6th step)
red
black
black
black
black
black



when does coloring actually occur? after SelectionColor?
 
DG said:
for(int i=0; i<10; i++)
{
txtLog.Text = i.ToString() + "\r\n" + txtLog.Text;

Here, the text is written using the colour that was last set. When you set
the colour below, it continues to use that colour here.
startSelection = txtLog.SelectionStart;
lenghtSelection = txtLog.SelectionLength;

Since you just replaced all the text, the selection was just lost.
Therefore,

txtLog.SelectionStart == txtLog.SelectionLength == 0

at this point.

txtLog.Select(startSelection, lenghtSelection);

This is equivalent to

txtLog.Select(0, 0);

(see above). However, this is also pointless for another reason: at the
top of the loop, you replace the text, whereupon these values are reset.

<snip>

Here's a working solution:

{
txtLog.Clear();
for(int i=0; i<10; i++)
{
txtLog.Select(0, 0);
txtLog.SelectionColor = i%2 == 0 ? Color.Black : Color.Red;
txtLog.SelectedText = i.ToString() + "\r\n";
}
}
 
i don't quite get it, how does SelectedText property work?
it inserts new text in RichTexbox?
 
DG said:
i don't quite get it, how does SelectedText property work?
it inserts new text in RichTexbox?

If SelectionLength is 0, then it inserts the text at position
SelectionStart. If SelectionLength is greater than 0, then it replaces the
current selection.
 
Thank you!


C# Learner said:
If SelectionLength is 0, then it inserts the text at position
SelectionStart. If SelectionLength is greater than 0, then it replaces
the
current selection.
 

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

Back
Top