Question

I like to delete last line of richtextbox which has ended with ; semicolumn. I like to delete this line until ; semicolumn that comes before the last semicolumn.

Example:

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

result should be:

hello do not delete this line;

My Code:

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();
        }
    }
Was it helpful?

Solution 3

Use this:

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 = "";
}

You did not specify the other scenarios(i.e, when the string does not contain ";") this code removes the string starting at ";" just before the last ";" to the last ";". It removes the last semicolon and texts after that, then finds the new last ";". finally removes the text after this ";"

OTHER TIPS

Found the solution here:

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

For those that find this question after all these years...

The solutions that use the .Text property or .Lines property end up removing the formatting from the existing text. Instead use something like this to preserve formatting:

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

Note that if your textbox is in ReadOnly mode, you can't modify SelectedText. In that case you need to set and reset ReadOnly like this:

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

I'm not sure exactly how the rich text box works, but something like

input = {rich text box text}
int index = text.lastIndexOf(";");
if (index > 0) 
{
    input = input.Substring(0, index);
}

// put input back in text box

How about that ?

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top