Reputation: 53
I wish to preserve the italics in the text while removing all the empty lines. I can't seem to be able to do it.
I used this code. It removes the empty lines but the text the italics.
richTextBox1.Text = Regex.Replace(richTextBox1.Text, @"^\s*$(\n|\r|\r\n)", "", RegexOptions.Multiline);
Upvotes: 1
Views: 2639
Reputation: 54433
The Golden Rule about RichTextBoxes
is to never change the Text
directly, once it has any formatting.
To add you use AppendText
and to change you need to use the Select, Cut, Copy & Paste..
methods to preserve the formatting!
string needle = "\r\r"; // only one possible cause of empty lines
int p1 = richTextBox1.Find(needle);
while (p1 >= 0)
{
richTextBox1.SelectionStart = p1;
richTextBox1.Select(p1, needle.Length);
richTextBox1.Cut();
p1 = richTextBox1.Find(needle);
}
For multiple needles you'll need to call the code multiple times, I'm afraid..
Upvotes: 2
Reputation: 3538
You can try removing empty lines from its Rtf Text. The sample code given below will work for you.
String[] allLines = richTextBox1
.Rtf
.Split( new string[] { Environment.NewLine },StringSplitOptions.None);
dynamic linesWithoutEmptyLines = from itm in allLines
where itm.Trim() != "\\par"
select itm;
richTextBox1.Rtf = string
.Join(Environment.NewLine, linesWithoutEmptyLines);
It will preserve the formatting of text and going to remove all the empty lines.
Upvotes: 1