Delete a specific line in a .NET RichTextBox

2020-04-10 06:04发布

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

9条回答
够拽才男人
2楼-- · 2020-04-10 06:43

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;
查看更多
Juvenile、少年°
3楼-- · 2020-04-10 06:45

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/

查看更多
叼着烟拽天下
4楼-- · 2020-04-10 06:47

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

查看更多
5楼-- · 2020-04-10 06:51

Based on tomanu's solution but without overhead

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.

查看更多
We Are One
6楼-- · 2020-04-10 06:52
int LineToDelete = 50;
List<string> lines = richTextBox1.Lines.ToList();
lines.Remove(LineToDelete);
richTextBox1.Lines = lines.ToArray();
查看更多
疯言疯语
7楼-- · 2020-04-10 06:54

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)

查看更多
登录 后发表回答