How can I store user-entered text in a formatted form?

fatih uyanık 225 Reputation points
2023-11-09T11:58:22.71+00:00

Hello

I am preparing a WPF project called "Smart Notes" with C#. There is a note creation window in this project. This window contains controls that hold the note title and note text. With RicTextBox, the user formats the desired parts of the text he enters with formatting such as font, color, bold-normal, italic.

What I want to do: I want to store the text entered by the user in a formatted format in the database and show it to the user as formatted whenever he wants. What method should I use to achieve this scenario?

Thanks.

Developer technologies C#
{count} votes

1 answer

Sort by: Most helpful
  1. Viorel 122.6K Reputation points
    2023-11-09T12:45:03.7733333+00:00

    For example, to obtain the formatted text in RTF format, try this:

    string rtf;
    
    TextRange tr = new TextRange( richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd );
    
    using( var ms = new MemoryStream( ) )
    {
        tr.Save( ms, DataFormats.Rtf );
    
        rtf = Encoding.ASCII.GetString( ms.GetBuffer( ), 0, checked((int)ms.Length) );
    }
    

    Then store the value of rtf. The varchar(max) is a suitable database type.

    To load it:

    string rtf = ... // load from database
    
    TextRange tr = new TextRange( richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd );
    
    using( var ms = new MemoryStream( Encoding.ASCII.GetBytes( rtf ) ) )
    {
        tr.Load( ms, DataFormats.Rtf );
    }
    

    Or, you can use the DataFormats.Xaml or DataFormats.XamlPackage formats, or store the bytes in binary format (varbinary(max)) without conversions to strings.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.