Append rich formatted text from 2 RichTextboxes into another RichTextBox in C#

喜欢而已 提交于 2020-07-22 10:30:05

问题


I have 3 RichTextBoxes: richTextBox1, richTextBox2 and richTextBox3.

I run the app and enter text into textbox 1 and 2.

So the text for richTextBox1 is "Test" and for richTextBox2 is "ing".

I now want to append that text together and put it into another richTextBox (preserving any formatting like bold, underlining, etc...)

So I try the following code:

richTextBox3.Rtf = richTextBox1.Rtf + richTextBox2.Rtf;

This doesn't cause any error but I only get the text from richTextBox1. So I get "Test".

So how do I copy the contents of the 2 RichTextBoxes while keeping the format?

Ta


回答1:


You will want to do this:

richTextBox3.Rtf = richTextBox1.Rtf
richTextBox3.Select(richTextBox3.TextLength, 0);
richTextBox3.SelectedRtf = richTextBox2.Rtf;

That should do the trick.




回答2:


Usage:

richTextBox3.Rtf = MergeRtfTexts(new RichTextBox[] { richTextBox1, richTextBox2});

RTF Merger Function:

    private string MergeRtfTexts(RichTextBox[] SourceRtbBoxes)
    {
        using (RichTextBox temp = new RichTextBox())
        {
            foreach (RichTextBox rtbSource in SourceRtbBoxes)
            {
                rtbSource.SelectAll();
                //move the end
                temp.Select(temp.TextLength, 0);
                //append the rtf
                temp.SelectedRtf = rtbSource.SelectedRtf;
            }
            return temp.Rtf;
        }
    }


来源:https://stackoverflow.com/questions/24954226/append-rich-formatted-text-from-2-richtextboxes-into-another-richtextbox-in-c-sh

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