Matt McManis
Matt McManis

Reputation: 4675

Remove Double LineBreak from RichTextBox to String

I'm using Visual Studio 2015, C#, WPF, XAML.

I copy the text from a RichTextBox to a string and remove any LineBreaks.

A LineBreak occurs if you press Shift+Enter. But just Enter causes a Double LineBreak.

Any text after the Double LineBreak gets cut off from TextRange and copying to the string.

What is this Double LineBreak and how do I remove it?

richtextbox linebreak


XAML

<RichTextBox x:Name="rtbMessage" Margin="10,10,10,50" />

C#

Paragraph p = new Paragraph();

// Get RichTextBox TextRange Method
//
public String MessageRichTextBox()
{
    rtbMessage.Document = new FlowDocument(p);

    TextRange textRange = new TextRange(
        rtbMessage.Document.ContentStart,
        rtbMessage.Document.ContentEnd
    );

    return textRange.Text;
}


// RichTextBox to String
// Remove LineBreaks
//
string message = MessageRichTextBox().Replace(Environment.NewLine, "");

Removal I have tried:

https://stackoverflow.com/a/6750310/6806643

Regex.Replace(MessageRichTextBox(), @"[\u000A\u000B\u000C\u000D\u2028\u2029\u0085]+", string.Empty);

.Replace(Environment.NewLine, "")
.Replace("\n", "")
.Replace("\r\n", "")
.Replace("\u2028", "")
.Replace("\u000A", "")
.Replace("\u000B", "")
.Replace("\u000C", "")
.Replace("\u000D", "")
.Replace("\u0085", "")
.Replace("\u2028", "")
.Replace("\u2029", "")

Upvotes: 2

Views: 1922

Answers (1)

DK.
DK.

Reputation: 3243

When you retrieve RichTextBox text like this

public String MessageRichTextBox()
{
    rtbMessage.Document = new FlowDocument(p);
    TextRange textRange = new TextRange(
        rtbMessage.Document.ContentStart,
        rtbMessage.Document.ContentEnd
    );
    return textRange.Text;
}

you modify the content of the rtbMessage, so you get the wrong content. I assume you somehow reference the 1st paragraph of the document in p and truncate the document to the 1st paragraph right there. Try to remove the line rtbMessage.Document = new FlowDocument(p); and see if it works for you?

When user hits Enter there is no double-LineBreak being inserted, but a new Paragraph is created. You can verify it by trying to place the caret to a presumably empty line there - if it's a double line break, there should be an empty line and the caret can be positioned on it.

Anyway, the document on your screenshot should have 2 paragraph blocks like this:

  • Paragraph 1: "Hello, world."
  • Paragraph 2: "This is a test.<LineBreak/>Example."

Hence my assumption is that when you re-create a document trying to retrieve its content as a text, you only retain the 1st paragraph there and discard the rest.

Upvotes: 2

Related Questions