C# – join lines

cparagraphrichtextbox

on a windows form, i have RichTextBox, with some text, in several lines. and one button on a form.

i wolud like when i click on that button, to join all richtextbox of lines in one line, but not to loose text style (like font family, color, etc.)

i can not do it with Replace, like \r\n, and not with the Replace(Environment.NewLine, "")……..
:-((

i have also tryed to replace \par and \pard, but still no luck…….

please help!!!


richTextBox1.Text = richTextBox1.Text.Replace(Environment.NewLine, "");

this one is not ok, because with that loose font definitions (color, bold, undesline etc).

ok, again to be more specific…

i have RichTextBox control, with 4 lines of text:

line 1
line 2
line 3
line 4

line 3 is colored red.

i need to get following:

line 1 line 2 line 3 line 4

(and that "line 3" be red as it was before).

when i try with

richTextBox1.Text = richTextBox1.Text.Replace(Environment.NewLine, " ");

… i get:

line 1
line 2   
line 34

"line 2" is colored red.

what do i have to do, to solve this problem?

Best Answer

This will work:

        // Create a temporary buffer - using a RichTextBox instead
        // of a string will keep the RTF formatted correctly
        using (RichTextBox buffer = new RichTextBox())
        {
            // Split the text into lines
            string[] lines = this.richTextBox1.Lines;
            int start = 0;

            // Iterate the lines
            foreach (string line in lines)
            {
                // Ignore empty lines
                if (line != String.Empty)
                {
                    // Find the start position of the current line
                    start = this.richTextBox1.Find(line, start, RichTextBoxFinds.None);

                    // Select the line (not including new line, paragraph etc)
                    this.richTextBox1.Select(start, line.Length);

                    // Append the selected RTF to the buffer
                    buffer.SelectedRtf = this.richTextBox1.SelectedRtf;

                    // Move the cursor to the end of the buffers text for the next append
                    buffer.Select(buffer.TextLength, 0);
                }
            }

            // Set the rtf of the original control
            this.richTextBox1.Rtf = buffer.Rtf;
        }
Related Topic