删除富文本框的最后一行

本文关键字:一行 最后 文本 删除 | 更新日期: 2023-09-27 17:52:43

我喜欢删除最后一行以;半圆柱。我喜欢删除这一行直到;在最后一个分列之前的分列。

例子:

hello do not delete this line;
hello this sentence will continue...
untill here;

结果应该是:

hello do not delete this line;
我的代码:

private void button1_Click_1(object sender, EventArgs e) {
        List<string> myList = richTextBox1.Lines.ToList();
        if (myList.Count > 0) {
            myList.RemoveAt(myList.Count - 1);
            richTextBox1.Lines = myList.ToArray();
            richTextBox1.Refresh();
        }
    }

删除富文本框的最后一行

找到解决方案:

RichTextBox1.Lines = RichTextBox1.Lines.Take(RichTextBox1.Lines.Length - 3).ToArray();

对于那些在这么多年后发现这个问题的人…

使用。text属性或。lines属性的解决方案最终会从现有文本中删除格式。相反,使用下面的代码来保留格式:

var i = textBox.Text.LastIndexOf("'n");
textBox.SelectionStart = i;
textBox.SelectionLength = o.TextLength - i + 1;
textBox.SelectedText = "";

注意,如果你的文本框处于只读模式,你不能修改SelectedText。在这种情况下,你需要像这样设置和重置ReadOnly:

textBox.ReadOnly = false;
textBox.SelectedText = "";
textBox.ReadOnly = true;

使用

var last = richTextBox1.Text.LastIndexOf(";");
if (last > 0)
{
   richTextBox1.Text = richTextBox1.Text.Substring(0, last - 1);
   var beforelast = richTextBox1.Text.LastIndexOf(";");
   richTextBox1.Text = richTextBox1.Text.Substring(0, beforelast + 1);
}
else
{
   richTextBox1.Text = "";
}

您没有指定其他场景(例如;E,当字符串不包含";"时)这段代码删除从";"开始的字符串,就在最后一个";"之前,直到最后一个";"。它删除最后一个分号和后面的文本,然后找到新的最后一个";"。最后删除";"之后的文本。"

我不确定富文本框是如何工作的,但是像

这样的东西
input = {rich text box text}
int index = text.lastIndexOf(";");
if (index > 0) 
{
    input = input.Substring(0, index);
}
// put input back in text box

怎么样?

string input = "your complete string; Containing two sentences";
List<string> sentences = s.Split(';').ToList();
//Delete the last sentence
sentences.Remove(sentences[sentences.Count - 1]);
string result = string.Join(" ", sentences.ToArray());
int totalcharacters = yourrtb.Text.Trim().Length;
int totalLines = yourrtb.Lines.Length;
string lastLine = yourrtb.Lines[totalLines - 1];
int lastlinecharacters = lastLine.Trim().Length;
yourrtb.Text = yourrtb.Text.Substring(0, totalcharacters - lastlinecharacters);