C# 删除 .NET RichTextBox 中的特定行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1329347/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 15:12:08  来源:igfitidea点击:

Delete a specific line in a .NET RichTextBox

c#.netwinformsrichtextbox

提问by leeeroy

How can I delete a specific line of text in a RichTextBox ?

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

回答by TLiebe

I don't know if there is an easy way to do it in one step. You can use the .Split function on the .Text property of the rich text box to get an array of lines

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

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

and then write something to re-assemble the array into a single text string after removing the line you wanted and copy it back to the .Text property of the rich text box.

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

Here's a simple example:

这是一个简单的例子:

        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;

If your rich text box was going to have more than 10 lines or so it would be a good idea to use a StringBuilder instead of a string to compose the new text with.

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

回答by David Basarab

Find the text to delete in a text range, found hereSet the text to empty, and now it is gone form the document.

在文本范围内找到要删除的文本,找到here将文本设置为空,现在它从文档中消失了。

回答by tomanu

Another solution:

另一种解决方案:

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

回答by Ali Issa

Try this:

尝试这个:

Dim lst As New ListBox  
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click  
            Me.Controls.Add(lst)  
            For Each cosa As String In Me.RichTextBox1.Lines  
                lst.Items.Add(cosa)  
            Next  
            lst.Items.RemoveAt(2) 'the integer value must be the line that you want to remove -1  
            Me.RichTextBox1.Text = String.Empty  
            For i As Integer = 0 To lst.Items.Count - 1  
                If Me.RichTextBox1.Text = String.Empty Then  
                    Me.RichTextBox1.Text = lst.Items.Item(i)  
                Else  
                    MeMe.RichTextBox1.Text = Me.RichTextBox1.Text & Environment.NewLine & lst.Items.Item(i).ToString  
                End If  
            Next  
        End Sub

http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/63647481-743d-4e55-9043-e0db5106a03a/

http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/63647481-743d-4e55-9043-e0db5106a03a/

回答by cnd

Based on tomanu's solution but without overhead

基于 tomanu 的解决方案但没有开销

int start_index = LogBox.GetFirstCharIndexFromLine(linescount);
int count = LogBox.GetFirstCharIndexFromLine(linescount + 1) - start_index;
LogBox.Text = LogBox.Text.Remove(start_index, count);

note that my linescount here is linescount - 2.

请注意,我这里的行数是行数 - 2。

回答by wondra

This also could do the trick (if you can handle things such as ++ in forms code). Keeps the text format. Just remember "ReadOnly" attribute work for both you and user.

这也可以解决问题(如果您可以在表单代码中处理诸如 ++ 之类的事情)。保持文本格式。请记住“只读”属性对您和用户都有效。

richTextBox.SelectionStart = richTextBox.GetFirstCharIndexFromLine(your_line);
richTextBox.SelectionLength = this.richTextBox.Lines[your_line].Length+1;
this.richTextBox.SelectedText = String.Empty;

回答by Dave Cousineau

Here is my unit tested implementation.

这是我的单元测试实现。

public static void DeleteLine([NotNull] this RichTextBox pRichTextBox, int pLineIndex) {
   if (pLineIndex < 0 || pLineIndex >= pRichTextBox.Lines.Length)
      throw new InvalidOperationException("There is no such line.");

   var start = pRichTextBox.GetFirstCharIndexFromLine(pLineIndex);
   var isLastLine = pLineIndex == pRichTextBox.Lines.Length - 1;
   var nextLineIndex = pLineIndex + 1;

   var end = isLastLine
      ? pRichTextBox.Text.Length - 1
      : pRichTextBox.GetFirstCharIndexFromLine(nextLineIndex) - 1;

   var length = end - start + 1;
   pRichTextBox.Text = pRichTextBox.Text.Remove(start, length);
}

Unit tests:

单元测试:

(used \ninstead of Environment.NewLinesince at least for me RTB is automatically replacing \r\nwith just \n)

(使用\n而不是Environment.NewLine因为至少对我来说 RTB 会自动替换\r\n为 just \n

[TestMethod]
public void TestDeleteLine_SingleLine() {
   var rtb = new RichTextBox();
   rtb.Text = "This is line1.\n";
   rtb.DeleteLine(0);
   var expected = "";
   Assert.AreEqual(expected, rtb.Text);
}

[TestMethod]
public void TestDeleteLine_BlankLastLine() {
   var rtb = new RichTextBox();
   rtb.Text = "\n";
   rtb.DeleteLine(1);
   var expected = "\n";
   Assert.AreEqual(expected, rtb.Text);
}

[TestMethod]
public void TestDeleteLine_SingleLineNoEOL() {
   var rtb = new RichTextBox();
   rtb.Text = "This is line1.";
   rtb.DeleteLine(0);
   var expected = "";
   Assert.AreEqual(expected, rtb.Text);
}

[TestMethod]
public void TestDeleteLine_FirstLine() {
   var rtb = new RichTextBox();
   rtb.Text = "This is line1.\nThis is line2.\nThis is line3.";
   rtb.DeleteLine(0);
   var expected = "This is line2.\nThis is line3.";
   Assert.AreEqual(expected, rtb.Text);
}

[TestMethod]
public void TestDeleteLine_MiddleLine() {
   var rtb = new RichTextBox();
   rtb.Text = "This is line1.\nThis is line2.\nThis is line3.";
   rtb.DeleteLine(1);
   var expected = "This is line1.\nThis is line3.";
   Assert.AreEqual(expected, rtb.Text);
}

[TestMethod]
public void TestDeleteLine_LastLine() {
   var rtb = new RichTextBox();
   rtb.Text = "This is line1.\nThis is line2.\nThis is line3.";
   rtb.DeleteLine(2);
   var expected = "This is line1.\nThis is line2.\n";
   Assert.AreEqual(expected, rtb.Text);
}

[TestMethod]
public void TestDeleteLine_OneBlankLine() {
   var rtb = new RichTextBox();
   rtb.Text = "\n";
   rtb.DeleteLine(0);
   var expected = "";
   Assert.AreEqual(expected, rtb.Text);
}

[TestMethod]
public void TestDeleteLine_BlankLines() {
   var rtb = new RichTextBox();
   rtb.Text = "\n\n\n\n\n";
   rtb.DeleteLine(2);
   var expected = "\n\n\n\n";
   Assert.AreEqual(expected, rtb.Text);
}

[TestMethod, ExpectedException(typeof(InvalidOperationException))]
public void TestDeleteLine_Exception_BeforeFront() {
   var rtb = new RichTextBox();
   rtb.Text = "\n\n\n\n\n";
   rtb.DeleteLine(-1);
}

[TestMethod, ExpectedException(typeof(InvalidOperationException))]
public void TestDeleteLine_Exception_AfterEnd() {
   var rtb = new RichTextBox();
   rtb.Text = "\n\n";
   rtb.DeleteLine(3);
}

回答by Rusty Nail

Lots of good answers, but I find many far to complicated.

很多很好的答案,但我发现很多问题很复杂。

string[] LinesArray = this.richTextBox1.Lines;

this.richTextBox1.Clear();

for (int line = 0; line < LinesArray.Length; line++)
{
if (!LinesArray[line].Contains("< Test Text To Remove >"))
{
this.richTextBox1.AppendText(LinesArray[line] + Environment.NewLine);
}
}

I hope this helps others some ;0)

我希望这对其他人有帮助;0)

回答by borg379

int LineToDelete = 50;
List<string> lines = richTextBox1.Lines.ToList();
lines.Remove(LineToDelete);
richTextBox1.Lines = lines.ToArray();