• RichTextBox CR/LF Text issues

    by  • March 29, 2012 • .NET, C# • 0 Comments

    It seems that sometimes when you get the text from a RichTextBox object, for instance to put it on the Clipboard, that the carriage return/line feeds are not handled properly. For instance the RichTextBox object may contain 2 lines of text, but its Text attribute may actually show those 2 lines concatenated together on 1 line.

    For instance in the RichTextBox you have:

    This is line 1
    This is line 2

    And its Text attribute shows:

    This is line 1This is line 2

    To work around this, you can iterate through the individual lines from the RichTextBox Lines attribute, and concat each line with the StringBuilder AppendLine() method.

    Here is an example:

    private System.Windows.Forms.RichTextBox richTextBox;
    private System.Windows.Forms.Button button;
    . . .
    private void button_Click(object sender, EventArgs e)
    {
      // Get lines one by one instead of using .Text attribute
      // of RichTextForm due to CR/LF issues.
      int sbLen = richTextBox.Text.Length
        + (richTextBox.Lines.Length << 1);
      StringBuilder sb = new StringBuilder(sbLen);
      foreach (String line in richTextBox.Lines) {
        sb.AppendLine(line);
      }
      // Place both text and RTF formats on the clipboard.
      DataObject cbData = new DataObject();
      cbData.SetData(DataFormats.Text, sb.ToString());
      cbData.SetData(DataFormats.Rtf, richTextBox.Rtf);
      Clipboard.SetDataObject(cbData);
    }

    Leave a Reply

    Your email address will not be published. Required fields are marked *


    *