Robert Cody
Robert Cody

Reputation: 179

How do I set the Richtextbox.rtf to a rich text string?

I am trying to add a header to the rich text in a RichTextBox, using VB.NET and Visual Studio 2017. According to the documentation, Richtextbox.rtf should allow me to get or set the rich text including control codes. However, I am unable to set *.rtf to a string containing rich text. I know that the rich text is correct because if I paste it into a *.rtf file, it is displayed correctly.

The test code looks like this:

   Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim hdr As String = "{\header This is a header}"
        Dim s As String = RichTextBox1.Rtf
        s = s.Insert(s.LastIndexOf("}"c) - 1, hdr)
        MsgBox(s)
        With RichTextBox1
            RichTextBox1.Rtf = s
            MsgBox(RichTextBox1.Rtf)
        End With
    End Sub

The string s is correctly formatted as rich text, but RichTextBox1.Rtf is unchanged after the assignment. What am I missing? If I can't assign RichTextBox1.Rtf this way, is there an alternative?

Upvotes: 1

Views: 3433

Answers (1)

Robert Cody
Robert Cody

Reputation: 179

Thanks again @PerpetualStudent!

The problem appears to be that the RichTextBox1.RTF field does not accept the "{\header This is a header}" control code. That is probably by design because a RichTextBox cannot display a header. I tried putting the control code in a different location in the rich text string, but that didn't work either.

I can edit the rich text in other ways (see below), but I cannot insert the header control code. That's unfortunate because it is part of the rich text standard. Anyhow, now that I know what the problem is, I can come up with a solution. A workaround might be to modify the print and save code of my rich text box print control form to add the header and footer in the print or save actions.

This works:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click With RichTextBox1 Dim s As String = .Rtf s = s.Replace("Hello", "Good morning") MsgBox(s) .Rtf = s MsgBox(.Rtf) End With End Sub

Upvotes: 1

Related Questions