Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a WPF rich textbox into a string

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?

like image 273
Asaf Avatar asked Nov 08 '10 15:11

Asaf


People also ask

What is RichTextBox WPF?

The RichTextBox control enables you to display or edit flow content including paragraphs, images, tables, and more. This topic introduces the TextBox class and provides examples of how to use it in both Extensible Application Markup Language (XAML) and C#.

What is the use of RichTextBox in C#?

In C#, RichTextBox control is a textbox which gives you rich text editing controls and advanced formatting features also includes a loading rich text format (RTF) files. Or in other words, RichTextBox controls allows you to display or edit flow content, including paragraphs, images, tables, etc.

What is the difference between TextBox and RichTextBox controls?

The RichTextBox is similar to the TextBox, but it has additional formatting capabilities. Whereas the TextBox control allows the Font property to be set for the entire control, the RichTextBox allows you to set the Font, as well as other formatting properties, for selections within the text displayed in the control.


1 Answers

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;
}
like image 144
Gavin Miller Avatar answered Oct 29 '22 19:10

Gavin Miller