Changing rich text box font color in loop
This seems like it should work to me but I can't seem to figure it out
public void ShowReport()
{
foreach (KeyValuePair<int, ReportSet> pair in ReportSets)
{
ReportText.Text += pair.Value.ReportSetText + Environment.NewLine;
foreach (string message in pair.Value.ReportMessages)
{
ReportText.Text += message;
开发者_如何转开发 ReportText.Select(ReportText.Text.LastIndexOf(message), message.Length);
ReportText.SelectionColor = pair.Value.Color;
}
ReportText.Text += Environment.NewLine;
}
this.Show();
}
As is, this changes no text color. If I remove the new line after the inner loop, it will change the color of the last message only. Tried removing all of the new lines just for s's and g's but the same result. Any ideas?
I'd suggest you use AppendText() instead of +=
to add your text, and avoid using LastIndexOf()
to compute your selection bounds. Clearing the selection after coloring it might also be a good idea:
foreach (KeyValuePair<int, ReportSet> pair in ReportSets) {
ReportText.AppendText(pair.Value.ReportSetText + Environment.NewLine);
foreach (string message in pair.Value.ReportMessages) {
int start = ReportText.TextLength;
ReportText.AppendText(message);
ReportText.Select(start, ReportText.TextLength - start);
ReportText.SelectionColor = pair.Value.Color;
ReportText.SelectionLength = 0;
}
ReportText.AppendText(Environment.NewLine);
}
精彩评论