如何使用C#比较两个richtextbox文本

时间:2011-07-21 20:16:56

标签: xml c#-3.0

我编写了一个逻辑来比较两个ricttext框内容,但是输出差异文本没有在预期的索引处突出显示。它在预期指数之前开始。我在下面给出了我使用的逻辑。

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;

        }
    }

谢谢, LOKESH。

2 个答案:

答案 0 :(得分:1)

您的方法没有问题,但是富文本框只能选择一次,您必须添加1。

执行以下操作:

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(结果中的字符串str)             {

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

现在在按钮点击事件中,将其调用为多次选择。虽然这会占用不必要的时间(写作时没有多想),但每次都会选择下一个。

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

答案 1 :(得分:0)

查找可能存在问题的换行符