12

I saw how to set a WPF rich text box in RichTextBox Class.

Yet I like to save its text to the database like I used to, in Windows Forms.

string myData = richTextBox.Text;
dbSave(myData);

How can I do it?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Asaf
  • 3,067
  • 11
  • 35
  • 54
  • Why use a RichTextBox, if you only want the text? Wouldnt it be better to just use a TextBox instead? :) – Arcturus Nov 08 '10 at 15:51

1 Answers1

23

At the bottom of the MSDN RichTextBox reference there's a link to How to Extract the Text Content from a RichTextBox

It's going to look like this:

public string RichTextBoxExample()
{
    RichTextBox myRichTextBox = new RichTextBox();

    // Create a FlowDocument to contain content for the RichTextBox.
    FlowDocument myFlowDoc = new FlowDocument();

    // Add initial content to the RichTextBox.
    myRichTextBox.Document = myFlowDoc;

    // Let's pretend the RichTextBox gets content magically ... 

    TextRange textRange = new TextRange(
        // TextPointer to the start of content in the RichTextBox.
        myRichTextBox.Document.ContentStart, 
        // TextPointer to the end of content in the RichTextBox.
        myRichTextBox.Document.ContentEnd
    );

    // The Text property on a TextRange object returns a string
    // representing the plain text content of the TextRange.
    return textRange.Text;
}
NoWar
  • 36,338
  • 80
  • 323
  • 498
Gavin Miller
  • 43,168
  • 21
  • 122
  • 188
  • 2
    +1 :this is a bit complicated for something so basic. It's useful to control start and finish yet in most of the time not needed and I still expect .text or .context etc. – Asaf Nov 08 '10 at 15:55
  • @Asaf I don't think this is that complicated, the RichTextBox is not a plain text document. There is formatting, styles, etc associated with a RichTextBox, and so it makes sense to have an Object based backing. – Gavin Miller Nov 08 '10 at 15:59
  • you may be right but I'm loosing my hair here quiet fast: basics like set text, clearText (=""), or putting the string value in a function are avoiding me.It may make sense but it's not friendly at all. – Asaf Nov 08 '10 at 16:10