Storing data of rich text box to database with formatting

39,843

To get the formatted text that will be saved in the db:

string rtfText; //string to save to db
TextRange tr = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd);
using (MemoryStream ms = new MemoryStream())
{
    tr.Save(ms, DataFormats.Rtf);
    rtfText = Encoding.ASCII.GetString(ms.ToArray());
}

To restore the formatted text retrieved from the db:

string rtfText= ... //string from db
byte[] byteArray = Encoding.ASCII.GetBytes(rtfText);
using (MemoryStream ms = new MemoryStream(byteArray))
{
    TextRange tr = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd);
    tr.Load(ms, DataFormats.Rtf);
}

You can also use XAML format instead, using DataFormats.XAML on load an save.

Share:
39,843
Amine Da.
Author by

Amine Da.

Intern at Microsoft. Working with : WPF, Universal apps 10 and .net .

Updated on October 15, 2021

Comments

  • Amine Da.
    Amine Da. over 2 years

    I am new at wpf and I want to store the data of the rich text box along with its formatting (Italic, colored, Bold..) into a database (Mysql). currently when i save the data, formatting is ignored. in addition, it shows all the text in the same line when i load it back to the rich text box from the database. Looking forward to your help and suggestions!

    public void save()
        {  
    
            MySqlConnection conn = new MySqlConnection(connString);
            MySqlCommand command = conn.CreateCommand();      
            string richText = new TextRange(rt1.Document.ContentStart,  rt1.Document.ContentEnd).Text;
    
            string s = WebUtility.HtmlEncode(richText); 
            command.Parameters.AddWithValue("@s", s);           
            command.CommandText = "insert into proc_tra (procedures) values (@s)";
            conn.Open();
            command.ExecuteNonQuery();
            conn.Close();
        }
    
    public void load()
    
        {   MySqlConnection conn = new MySqlConnection(connString);
            MySqlCommand command = conn.CreateCommand();
            command.CommandText = "select * from proc_tra where id_pt=4";
            rt1.Document.Blocks.Clear();            
            conn.Open();            
            MySqlDataReader dr;
            dr = command.ExecuteReader();
            string k="";           
            while (dr.Read())
            {              
                k += dr["procedures"].ToString();
            }
            var p = new Paragraph();
            var run = new Run();
            run.Text = WebUtility.HtmlDecode(k);
            p.Inlines.Add(run);
            rt1.Document.Blocks.Add(p);
        }
    
  • Amine Da.
    Amine Da. about 11 years
    thx for the answer but ‘HttpUtility’ does not exist in the current context even if I add system.web
  • Amine Da.
    Amine Da. about 11 years
    I 've added reference to System.Web and Used using System.Web but still not working
  • Timothy Randall
    Timothy Randall about 11 years
    Make sure your project is not targeting one of the Client Profile frameworks in your project properties.
  • Amine Da.
    Amine Da. about 11 years
    I already checked and I am targeting .Net framework 4.5 (not the client profile)
  • Timothy Randall
    Timothy Randall about 11 years
    Since you are using .NET 4.5 you can swap out the HTTPUtility.HtmlEncode/Decode for this: msdn.microsoft.com/en-us/library/…
  • Amine Da.
    Amine Da. about 11 years
    thx again for your help, I swaped to Webutility, I can save data to mysql but when i load it back still no formatting. I've updated my post with my code.
  • Amine Da.
    Amine Da. about 11 years
    maybe the (selectedDataFromMySQL).tostring() with the datareader is the problem
  • Sharad Ag.
    Sharad Ag. over 8 years
    Dosent work dear, Shows richtextbox doesnt have any definition called Document.
  • TEK
    TEK about 8 years
    @SharadAg. This is for WPF, not WinForms.
  • Connor Mcgrann
    Connor Mcgrann over 6 years
    If you are receiving the error "Reference to a non-shared member requires an object reference." Note that he is using the "richTextBox" as a variable and not the class. This means you need the following code to allow the TextRange to work. 'RichTextBox richTextBox = default(RichTextBox);' Great Solution btw, thumbs up.
  • Admin
    Admin about 2 years
    This thread is for WPF. Thus your answer here is out of the thread scope. However your answer could be 'valid' if you have shared a working alternative for WinForms. That would help people looking for a WinForms solution.