Storing data of rich text box to database with formatting
To get the formatted text that will be saved in the db:
string rtfText; //string to save to dbTextRange 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 dbbyte[] 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.
Try something like this:
RichTextBox richTextBox = new RichTextBox();string richText = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd).Text;
Then, when going to save it to MySQL, you can build your query like this:
string query = "INSERT INTO blah VALUES ('" + HTTPUtility.HtmlEncode(richText) + "');
This will ensure that your content stays formatted correctly.
Finally when you perform your select to load the content back into the RichTextBox take the string you get and use:
HTTPUtility.HtmlDecode(selectedDataFromMySQL);
or, more completely:
richTextBox.Document.Blocks.Clear();richTextBox.Document.Blocks.Add(new Paragraph(HTTPUtility.HtmlDecode(selectedDataFromMySQL);
While I haven't done this in a while myself, I believe there is an extension for the WPF and the control that includes a Text property so that may prove useful as well.