The Mask
The Mask

Reputation: 17457

highlight the '#' until line end in richtextbox

I have the following text in my RIchTextBox:

foo:baa#done baa
a:b#pending  ee

and I want highlight all after # and before " "(espace)

How I do this? I tried make the end as IndexOf of \t or " " but it returns -1.

My code(not working as expected):

        string[] lines = list.Lines;
        string line;

        for (int i = 0, max = lines.Length; i < max; i++)
        {
            line = lines[i];
            int start = list.Find("#");
            int end = ??? // I tried list.Find("\t") and list.Find(" ")
            if (-1 != start || -1 != end)
                {
                    list.Select(start, end);
                    list.SelectionColor = color;
                }
          }

list is an RichTextBox

Upvotes: 1

Views: 954

Answers (3)

ojlovecd
ojlovecd

Reputation: 4902

try this:

        string[] lines = list.Lines;
        string line;
        int len = 0;
        for (int i = 0, max = lines.Length; i < max; i++)
        {
            line = lines[i];
            int j = i == 0 ? 0 : len;
            string str = Regex.Match(line, @"#.*$").Value;
            if (!string.IsNullOrEmpty(str))
            {
                int start = list.Find(str, j, RichTextBoxFinds.None);
                if (start != -1)
                {
                    list.Select(start, str.Length);
                    list.SelectionColor = Color.Red;
                }
                len += line.Length;
            }
        }

Upvotes: 2

Hans Passant
Hans Passant

Reputation: 942318

Use GetLineFromCharIndex() to get the line number of the Find() method return value. Then GetFirstCharIndexFromLine(line + 1) to know where the next line starts. That gives you the SelectionStart and SelectionLength values you need to highlight the text.

Upvotes: 3

neeKo
neeKo

Reputation: 4280

Maybe you should use line.IndexOf instead of list.Find?

In short, you seem to be searching for characters in your List control, not in the string line.

Upvotes: 1

Related Questions