Edit

Share via


How to: Extract the Text Content from a RichTextBox

This example shows how to extract the contents of a RichTextBox as plain text.

Describe a RichTextBox control

The following Extensible Application Markup Language (XAML) code describes a named RichTextBox control with simple content.

<RichTextBox Name="richTB">
  <FlowDocument>
    <Paragraph>
      <Run>Paragraph 1</Run>
    </Paragraph>
    <Paragraph>
      <Run>Paragraph 2</Run>
    </Paragraph>
    <Paragraph>
      <Run>Paragraph 3</Run>
    </Paragraph>
  </FlowDocument>
</RichTextBox>

Code example with RichTextBox as an argument

The following code implements a method that takes a RichTextBox as an argument, and returns a string representing the plain text contents of the RichTextBox.

The method creates a new TextRange from the contents of the RichTextBox, using the ContentStart and ContentEnd to indicate the range of the contents to extract. ContentStart and ContentEnd properties each return a TextPointer, and are accessible on the underlying FlowDocument that represents the contents of the RichTextBox. TextRange provides a Text property, which returns the plain text portions of the TextRange as a string.

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

    // The Text property on a TextRange object returns a string
    // representing the plain text content of the TextRange.
    return textRange.Text;
}
Private Function StringFromRichTextBox(ByVal rtb As RichTextBox) As String
        ' TextPointer to the start of content in the RichTextBox.
        ' TextPointer to the end of content in the RichTextBox.
    Dim textRange As New TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd)

    ' The Text property on a TextRange object returns a string
    ' representing the plain text content of the TextRange.
    Return textRange.Text
End Function

See also