配置:
总结:通过for循环向rtb发送单词;根据内容格式化它们(“OK”显示为绿色,“failed”显示为红色)。
代码:
for (int i = 0; i < inputValues.Length; i++)
{
//checking if the value is OK or not
string answer = functionReturningString(inputValues[i], referenceValue);
textBox4.Text += answer; //and sending the result string to text box
}
现在我只是尝试选择最后添加的字符串,并根据其内容对其进行格式化。
textBox4.SelectAll();
textBox4.Select(textBox4.SelectedText.Length - answer.Length, answer.Length);
if (answer == "OK")
{
textBox4.SelectionColor = Color.Green;
} else {
textBox4.SelectionColor = Color.Red;
}
textBox4.Refresh();//I want to see every value as soon as added
textBox4.Text += "\r\n"; //adding space between words
至于结果,它最终会对rtb中的所有单词使用“SelectionColor”。
问:如何确保以前格式化的单词不会再次改变颜色?
更新:建议的解决方案也不起作用。单词将以正确的颜色显示(首先)。然后添加下一个单词,整个框的颜色会发生变化。
答案 0 :(得分:1)
序列应该是这样的(假设你从空的富文本框开始):
using System;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
namespace Tests
{
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var form = new Form();
var richTextBox = new RichTextBox { Dock = DockStyle.Fill, Parent = form };
var button = new Button { Dock = DockStyle.Bottom, Parent = form, Text = "Test" };
button.Click += (sender, e) =>
{
Color TextColor = Color.Black, OKColor = Color.Green, FailedColor = Color.Red;
var questions = Enumerable.Range(1, 20).Select(n => "Question #" + n).ToArray();
var random = new Random();
richTextBox.Clear();
for (int i = 0; i < questions.Length; i++)
{
richTextBox.SelectionColor = TextColor;
richTextBox.AppendText(questions[i] + ":");
bool ok = (random.Next() & 1) != 0;
richTextBox.SelectionColor = ok ? OKColor : FailedColor;
richTextBox.AppendText(ok ? "OK" : "Failed");
richTextBox.SelectionColor = TextColor;
richTextBox.AppendText("\r\n");
}
};
Application.Run(form);
}
}
}
这是一个模拟你所描述的案例的例子(如果我理解正确的话):
{{1}}
产生以下