Appending Contents of two RichTextbox as a single RichText string

前端 未结 4 1720
难免孤独
难免孤独 2020-12-11 16:02

I want to append the contents of two rich text boxes in a Windows Forms .Net application; say: stringText = richtextbox1.Rtf + richtextbox2.Rtf; The strin

相关标签:
4条回答
  • 2020-12-11 16:21

    I know it's old question, but it seems to be a common one. Thus, I'm gonna add my answer to this, cause the marked answer make RTF's to concatenate, but it also gives an extra new line, every time.

    This would be:

    RichTextBoxSource.Select(0,RichTextBoxSource.TextLength);
    RichTextBoxTarget.SelectedRtf = richTextBoxSource.SelectedRtf;
    

    It's easy and works fine. Hope it will help somebody:)

    0 讨论(0)
  • 2020-12-11 16:26

    Try this:

    richTextBoxTarget.Select(richTextBoxTarget.TextLength, 0);
    richTextBoxTarget.SelectedRtf = richTextBoxSource.Rtf;
    

    This merges the contents of richTextBoxSource to the end of richTextBoxTarget. It automatically creates valid RTF with only one \rtf tag.
    To de-merge, also use Selectand SelectedRtf. The only requirement here is, that you need to know, at what position you want to split.

    0 讨论(0)
  • 2020-12-11 16:27

    Not sure if this is useful, but here's the above code re-formatted into an extension method. This lets you say:

    textBox.AppendRtf(someRtfString)
    

    which handily matches up with the RichTextBox class's AppendText() method.

    ''' <summary>
    ''' Appends the provided RTF-formatted string to the provided <see cref="RichTextBox"/>.
    ''' </summary>
    <Extension()> _
    Public Sub AppendRtf(ByVal rtbTextBox As RichTextBox, ByVal strRtf As String)
        rtbTextBox.Select(rtbTextBox.TextLength, 0)
        rtbTextBox.SelectedRtf = strRtf
    End Sub
    
    0 讨论(0)
  • 2020-12-11 16:32

    well since I can't comment Pawel anwser, I must add that besides his code:

    RichTextBoxSource.Select(0,RichTextBoxSource.TextLength);
    RichTextBoxTarget.SelectedRtf = richTextBoxSource.SelectedRtf;
    

    you should add if you want the new text to be always on the top

    RichTextBoxTarget.Select(0,0);
    

    or if you want it to be always on the bottom

    RichTextBoxTarget.Select(RichTextBoxTarget.TextLength,0);
    

    So you also have control of the position like in Daniel answer, even if the target richtextbox is clickable.

    0 讨论(0)
提交回复
热议问题