简体   繁体   中英

RichTextBox RTF issue

I have a RichTextBox in Win form application with formating facilities like bold, italics, alignment etc options, right clicking on RTB opens ContexttoolStripmenu with option of inserting Client Address from database, which inserts a string "$[ClientAddress]" in the RTB text. When the save button is clicked $[ClientAddress] is replaced with actual address from database (which is in rtf format as under:

string rtfText = richTextBox.Rtf;
rtfText = rtfText.Replace("$[ClientAddress]", $address);

The problem here is that all formationg/styling done on "$[ClientAddress]" in the rich text box is lost when it is replaced by actual address string (in rtf format) from database.

How can we pass the styling(formating) carried on $[ClientAddress] to the text that replaces $[ClientAddress].

If address is passed as plain Text instead of rtf text from database then the formating stays but the line breaks between different lines of address are lost and address is printed in one straight line like:

39 East Tamaki Road, Papatoetoe, Auckland, New Zealand instead of the correct way as below as originally entered :
39 East Tamaki Road
Papatoetoe
Auckland
New Zealand

I hope I have been able to make my problem clear.

Have you considered the old paste it from the clipboard hack?

Below is a proof-of-concept on a winform with a richtextbox (rtb1) and a button (button1). Sorry, it's in VB...

Public Class Form1

  Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click

    ' This Richtextbox just to create the text that's in the database.

    Dim rtb2 As New RichTextBox

    rtb2.Text = "39 East Tamaki Road" & vbCrLf & "Papatoetoe" & vbCrLf & "Auckland, New Zealand"
    rtb2.SelectAll()
    rtb2.SelectionFont = New Font("Courier", 20)
    rtb2.SelectionColor = Color.Blue


    ' This would be Clipboard.SetData(TextDataFormat.Rtf, $address)

    Clipboard.SetData(TextDataFormat.Rtf, rtb2.SelectedRtf)

    rtb2.DeselectAll()
    rtb2.Clear()


    ' This is adding text to an existing richtextbox and then pasting in the replacement text.
    Dim sPlaceHolder As String = "$[ClientAddress]"

    rtb1.Clear()

    rtb1.Text = "This is some random text plus the whole " & vbCrLf & sPlaceHolder & vbCrLf & "Place holder above."
    rtb1.SelectAll()
    rtb1.SelectionFont = New Font("Arial", 10)
    rtb1.SelectionColor = Color.DarkRed
    rtb1.DeselectAll()

    Dim istart As Integer = rtb1.Find(sPlaceHolder)
    Dim ilength As Integer = sPlaceHolder.Length

    rtb1.SelectionStart = istart
    rtb1.SelectionLength = ilength

    rtb1.SelectedRtf = Clipboard.GetData(TextDataFormat.Rtf)


  End Sub
End Class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM