[英]How to remove empty lines while preserving the formatting of the richtextbox in c#
我希望在刪除所有空行時保留文本中的斜體。 我似乎無法做到這一點。
我用過這段代碼。 它刪除空行但文本為斜體。
richTextBox1.Text = Regex.Replace(richTextBox1.Text, @"^\s*$(\n|\r|\r\n)", "", RegexOptions.Multiline);
關於RichTextBoxes
的黃金法則一旦有任何格式,就永遠不會直接更改Text
。
要添加您使用AppendText
並更改您需要使用Select, Cut, Copy & Paste..
方法來保留格式!
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);
}
對於多針,您需要多次調用代碼,我擔心..
您可以嘗試從其Rtf文本中刪除空行。 下面給出的示例代碼適合您。
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);
它將保留文本的格式並刪除所有空行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.