Consider a RichTextBox which has 400 lines and includes a number of words and lines in diffident colours.
Is it possible to remove the first 100 lines of this text box, while the colour of remaining words are reserved. Currently, I am using the below code to remove lines, but It is not able to keep colours.
if (rtb.Lines.Count() > 400)
rtb.Lines = rtb.Lines.Skip(100).ToArray();
You can't use the
Lines
property if you want to preserve the formatting.Lines
is derived from TextBoxBase. You need to use the Rtf property and parse the lines yourself in the string you get back. If you want to just get the line count and then parse the RTF then you could do something like:You would need to look at the RTF specification to accurately pull out the actual lines. A line break is indicated by the tag
\par
. The line that would be tricky to deal with is the first line because it may contain extra information before the actual first line text.Use the SelectionText property. First select the lines you want to remove, then remove them by setting SelectionText to an empty string. Like this:
This preserves the formatting of all the other lines. This can cause visible flicker on the UI, you can suppress that by implementing the Begin/EndUpdate methods as shown here.
.SelectedText = "" throws a Windows ding in my application
So I found a second solution which is to play with .Lines property