Export (0) Print
Expand All

How to: Extract the Text Content from a RichTextBox

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

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>

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.

		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
Show:
© 2014 Microsoft