removing RichTextBox lines while keeping the colour of remaining lines in C#

萝らか妹 提交于 2019-11-28 14:02:40
Hans Passant

Use the SelectionText property. First select the lines you want to remove, then remove them by setting SelectionText to an empty string. Like this:

   richTextBox1.SelectionStart = 0;
   richTextBox1.SelectionLength = richTextBox1.GetFirstCharIndexFromLine(200);
   richTextBox1.SelectedText = "";

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.

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:

// NOTE: I am using Length rather than Count() because the array already knows its length
if (rtb.Lines.Length > 400)
{
    // Parse the rtf here to remove the unwanted lines and preserve the format
}

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.

.SelectedText = "" throws a Windows ding in my application

So I found a second solution which is to play with .Lines property

if (nbLines > maxLines)
{
    Array.Copy(rtfBox.Lines, 1,
               rtfBox.Lines, 0, rtfBox.Lines.Length - 1);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!