【问题标题】:How to remove empty lines while preserving the formatting of the richtextbox in c#如何在c#中保留richtextbox格式的同时删除空行
【发布时间】:2014-11-03 06:32:37
【问题描述】:

我希望在删除所有空行的同时保留文本中的斜体。我好像做不到。

我使用了这个代码。它删除了空行,但文本为斜体。

richTextBox1.Text = Regex.Replace(richTextBox1.Text, @"^\s*$(\n|\r|\r\n)", "", RegexOptions.Multiline);

【问题讨论】:

    标签: c# formatting richtextbox removing-whitespace preserve


    【解决方案1】:

    关于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);
    }
    

    恐怕你需要多次调用代码..

    【讨论】:

      【解决方案2】:

      您可以尝试从其 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);
      

      它将保留文本的格式并删除所有空行。

      【讨论】:

      • +1 表示包含\\par -1 表示假设Environment.NewLine 是一个好主意。它几乎从来没有......
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-22
      • 2021-11-19
      • 1970-01-01
      • 2013-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多