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">
      <Run>Paragraph 1</Run>
      <Run>Paragraph 2</Run>
      <Run>Paragraph 3</Run>

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
Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
© 2015 Microsoft