删除.NET RichTextBox中的特定行

lee*_*roy 3 .net c# richtextbox winforms

如何删除RichTextBox中的特定文本行?

小智 5

另一种方案:

private void DeleteLine(int a_line)
{
    int start_index = richTextBox.GetFirstCharIndexFromLine(a_line);
    int count = richTextBox.Lines[a_line].Length;

    // Eat new line chars
    if (a_line < richTextBox.Lines.Length - 1)
    {
        count += richTextBox.GetFirstCharIndexFromLine(a_line + 1) -
            ((start_index + count - 1) + 1);
    }

    richTextBox.Text = richTextBox.Text.Remove(start_index, count);
}
Run Code Online (Sandbox Code Playgroud)


TLi*_*ebe 1

不知道有没有一种简单的方法可以一步完成。您可以在富文本框的 .Text 属性上使用 .Split 函数来获取行数组

string[] lines = richTextBox1.Text.Split( "\n".ToCharArray() )
Run Code Online (Sandbox Code Playgroud)

然后编写一些内容,在删除所需的行后将数组重新组装成单个文本字符串,并将其复制回富文本框的 .Text 属性。

这是一个简单的例子:

        string[] lines = richTextBox1.Text.Split("\n".ToCharArray() );


        int lineToDelete = 2;           //O-based line number

        string richText = string.Empty;

        for ( int x = 0 ; x < lines.GetLength( 0 ) ; x++ )
        {
            if ( x != lineToDelete )
            {
                richText += lines[ x ];
                richText += Environment.NewLine;
            }
        }

        richTextBox1.Text = richText;
Run Code Online (Sandbox Code Playgroud)

如果您的富文本框将包含超过 10 行左右,那么最好使用 StringBuilder 而不是字符串来组成新文本。

  • 随着行数的增加,这会变得很慢。 (2认同)