c#如何为richtextbox中的每一行着色

时间:2017-06-02 12:59:58

标签: c# richtextbox

我需要为每一行着色取决于每个字符串表单列表中的最后一个字符。这是我的代码,它始终将最后一行设为绿色。它有什么问题?

List<string> plik = File.ReadAllLines(path).ToList();
        string pom;
        int size = plik.Count;
        richTextBox1.Clear();
        for (int i = 0; i < size; i++)
        {
            richTextBox1.Text += "[" + i.ToString() + "]" + "  " + plik[i] + Environment.NewLine;
            pom =plik[i];
             richTextBox1.Select(richTextBox1.GetFirstCharIndexFromLine(i), richTextBox1.Lines[i].Length);
           // richTextBox1.Select(0, pom.Length);
            if (pom.Substring(pom.Length - 1) == "n")
            {
                richTextBox1.SelectionBackColor = pom.Substring(pom.Length - 1) == "n" ? Color.Red :Color.Red;
            }
            if(pom.Substring(pom.Length - 1) != "n")
            {
                richTextBox1.SelectionBackColor = pom.Substring(pom.Length - 1) != "n"?Color.Green:Color.Green;                  
            }
        }      

2 个答案:

答案 0 :(得分:1)

只需替换

richTextBox1.Text += "[" + i.ToString() + "]" + "  " + plik[i] + Environment.NewLine;

通过

richTextBox1.AppendText("[" + i.ToString() + "]" + "  " + plik[i] + Environment.NewLine);

答案 1 :(得分:0)

附加文本而不是整体修改它。使用+=将替换整个字符串,因此您每次都会丢失设置的颜色。请改用AppendText

您还可以删除代码中不必要的if。这应该有效:

for (int i = 0; i < size; i++)
{
    richTextBox1.AppendText("[" + i.ToString() + "]" + "  " + plik[i] + Environment.NewLine);
    richTextBox1.Select(richTextBox1.GetFirstCharIndexFromLine(i), richTextBox1.Lines[i].Length);
    richTextBox1.SelectionBackColor = plik[i][plik[i].Length - 1] == 'n' ? Color.Red : Color.Green;
}