Sun
Sun

Reputation: 4718

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

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

Upvotes: 1

Views: 1864

Answers (2)

khan
khan

Reputation: 4489

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

Upvotes: 2

aydjay
aydjay

Reputation: 868

You will want to do this:

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

That should do the trick.

Upvotes: 5

Related Questions