简体   繁体   中英

c# how to color each lines in richtextbox

I need to color each line depends on the last char in each string form list. This is my code and it's always make the last line green. What's wrong with it?

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;                  
            }
        }      

just replace

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

by

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

Append the text instead of modifying it in whole. Using += will replace the entire string and hence you'll lose the set color each time. Use AppendText instead.

Also you can remove the unnecessary if s in your code. This should work:

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM