How to compare two richtextbox text using C#

巧了我就是萌 提交于 2019-12-25 08:39:20

问题


I have written a logic to compare two ricttext boxes content, but the output difference text is not highlighted at the expected index. It starts ahead of the expected index. I have given below the logic i have used.

private void CompareRichTextContents(RichTextBox target, RichTextBox dest)
    {
        string[] targetLines = target.Lines;
        string[] destLine = dest.Lines;
        List<string> result=targetLines.Except(destLine).ToList<string>();
        foreach (string str in result)
        {

            int lineIndex=Array.IndexOf(targetLines, str);
            int lineCount=0;
            for (int index = 0; index < lineIndex; index++)
            {
                lineCount+=targetLines[index].Length;
            }
            target.SelectionBackColor = Color.Yellow;
            target.SelectionColor = Color.Black;
            target.SelectionStart = lineCount;
            target.SelectionLength = str.Length;

        }
    }

Thanks, Lokesh.


回答1:


look for line feeds that may be the problem




回答2:


Your method is allright however rich textbox only selects one time further, you have to add 1.

Do as below:

private int CompareRichTextContents(RichTextBox target, RichTextBox dest) { int counter = 0; string[] targetLines = target.Lines; string[] destLine = dest.Lines; List result = targetLines.Except(destLine).ToList(); foreach (string str in result) {

            int lineIndex = Array.IndexOf(targetLines, str);
            int lineCount = 0;
            for (int index = 0; index < lineIndex; index++)
            {
                lineCount += targetLines[index].Length+1;
            }
            target.SelectionBackColor = Color.Yellow;
            target.SelectionColor = Color.Black;
           // target.Select(lineCount, str.Length);
             target.SelectionStart = lineCount;
             target.SelectionLength = str.Length;
             counter++;

        }
        return counter; 
    }

Now in button click event, call it as many times as many selections. Though this is calling unnecessary time (writing without thinking much) but each time it will select the next one.

 private void button1_Click(object sender, EventArgs e)
        {
           int counter= CompareRichTextContents(this.richTextBox1Body, this.richTextBox2Body);
           for (int i = 0; i < counter; i++)
               CompareRichTextContents(this.richTextBox1Body, this.richTextBox2Body);
        } 


来源:https://stackoverflow.com/questions/6782195/how-to-compare-two-richtextbox-text-using-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!